表达式< Func> T,bool>方法参数
问题描述:
我正在尝试创建一个通用方法来返回表达式的字符串版本:
I'm trying to make a generic method that returns the string version of an expression:
public string GetExpressionString(Expression<Func<T, bool>> expr) where T: class
{
return exp.Body.ToString();
}
无法解析符号T
如果我将 T
更改为硬编码类型,效果很好.
Works well if I change T
to a hard coded type.
我想念什么?
答
您需要将 T
声明为方法的通用类型参数:
You'll need to declare T
as a generic type parameter on the method:
public string GetExpressionString<T>(Expression<Func<T, bool>> exp)
where T: class
{
return exp.Body.ToString();
}
// call like this
GetExpressionString<string>(s => false);
GetExpressionString((Expression<Func<string, bool>>)(s => false));
或者在父类上:
public class MyClass<T>
where T: class
{
public string GetExpressionString(Expression<Func<T, bool>> exp)
{
return exp.Body.ToString();
}
}
// call like this
var myInstance = new MyClass<string>();
myInstance.GetExpressionString(s => false);
进一步阅读: