我想知道是否可以在C#中使用表达式作为变量/参数.我想做这样的事情:
int x = 0;
public void g()
{
bool greaterThan = f("x>2");
bool lessThan = f("x<2");
}
public bool f(Expression expression)
{
if(expression)
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
这是我不想做的事情:
int x = 0;
public void g()
{
bool greaterThan = f(x, '<', 2);
}
public bool f(int x, char c, int y)
{
if(c == '<')
return x < y;
if(c == '>')
return x > y;
}
Run Code Online (Sandbox Code Playgroud)
我真正得到的是一种方法,可以使用每个开关或一系列if语句:<> <=> = ==!=.有办法吗?
编辑:假设表达式是一个字符串,如"x <2".有没有办法从字符串转到谓词而不使用条件上的一系列if语句?
Sam*_*uel 11
它很可能,只是没有你的确切语法.
int x = 0;
public void g()
{
bool greaterThan = f(i => i > 2, x);
bool lessThan = f(i => i < 2, x);
}
public bool f(Func<int,bool> expression, int value)
{
return expression(value);
}
Run Code Online (Sandbox Code Playgroud)
实际上,这应该更接近你想要的.
int x = 0;
public void g()
{
bool greaterThan = f(() => x > 2);
bool lessThan = f(() => x < 2);
}
public bool f(Func<bool> expression)
{
return expression();
}
Run Code Online (Sandbox Code Playgroud)
如果你想说f("x < 2"),那几乎是不可能的.忽略解析它(可能会讨厌),你必须捕获x的值,但它只是一个字符f,这使得它几乎不可能.
如果你真的想传递代码,你想要一个谓词:
int x = 0;
public void g()
{
bool greaterThan = f(i => i>2, x);
bool lessThan = f(i => i<2, x);
}
public bool f(Predicate<int> expression, int value)
{
return expression(value);
}
Run Code Online (Sandbox Code Playgroud)
否则,如果您只是在第一个示例中替换bool,Expression您的代码将编译得很好:
int x = 0;
public void g()
{
bool greaterThan = f(x>2);
bool lessThan = f(x<2);
}
public bool f(bool expression)
{
if(expression)
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
除非我遗漏了什么......为什么你不这样做:
bool greaterThan = x > 5;
bool lessThan = x < 5;
Run Code Online (Sandbox Code Playgroud)
布尔比较已经是一个表达式......
编辑:
所以对于你的功能,只需传递一个bool:
public void f(bool expression)
{
// expression is either true or false...
}
f(x<5); // called like this
Run Code Online (Sandbox Code Playgroud)