我可以获得作为 bool 传递到函数中的条件的字符串表示形式吗?
我知道这个标题可能真的很难理解,很难想出一个合适的标题,但这就是我想做的事情的本质。
基本上我想要一个像这样的方法:
void Validate(bool validation)
{
if (!validation)
{
throw new Exception();
}
}
然后我想这样调用它:
try
{
Validate(1 > 2);
}
catch (Exception e)
{
// This is where I would output the error to the user
}
我想要得到 1 > 2
部分作为字符串,而不将其定义为其他地方的字符串,或者将字符串计算为 bool
,或者使用谓词,或者使用外部方法。理想情况下,这可以通过反射来完成。我也会接受关于更好的方式来做我想做的事情的建议。假设 bool
可以是任何内容:1 > 2
、“奶酪”!=“火腿”
、objectA == objectB
等。
I know the title is probably really hard to understand, it was hard to think of a proper title, but here's the essence of what I want to do.
Basically I want to have a method like this:
void Validate(bool validation)
{
if (!validation)
{
throw new Exception();
}
}
And then I want to call it like:
try
{
Validate(1 > 2);
}
catch (Exception e)
{
// This is where I would output the error to the user
}
I want to get the 1 > 2
part as a string without defining it as one elsewhere, or evaluating a string to a bool
, or using predicates, or using external methods. Ideally this would be done via reflection. I'll also take suggestions on a better way to do what I want to do. Assume that the bool
could be anything: 1 > 2
, "cheese" != "ham"
, objectA == objectB
, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。 碰巧可以(我想,在 Python 中,人们可以将这样的东西一起破解,尽管它不会很漂亮,不会可靠地工作并且需要手头有源代码),但通常:
在您寻找一些令人讨厌的黑客来模拟这一点之前,请检查在编译期间添加字符串文字是否更容易。
You can't. Well, perhaps you happen to can (in Python, one could hack something like this together, I suppose, although it wouldn't be pretty, wouldn't work reliably and would require having the source code at hand), but generally:
Before you're looking for some nasty nasty hack to emulate this, check if it isn't easier to add a string literal during compilation.
您能够得到的最接近的是使用 lambda 表达式,这看起来会产生以下效果:
虽然,老实说,我不确定它是否值得麻烦,并且您不会想在紧密循环,由于 lambda 表达式的动态编译(尽管如果需要,您可以缓存编译结果)
The closest you are going to be able to get is to use lambda expressions, which would look something to the effect of:
Though, honestly, I'm not sure it's worth the trouble, and you wouldn't want to use it in a tight loop, due to the dynamic compilation of the lambda expression (though you could possibly cache the result of the compilation if necessary)