Expression<Func<T, bool>> method argument

非 Y 不嫁゛ 提交于 2021-02-16 20:07:08

问题


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();
}

Cannot resolve symbol T

Works well if I change T to a hard coded type.

What did I miss?


回答1:


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));

Or on the parent class:

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);

Further Reading:

  • Generic Methods (C# Programming Guide)



回答2:


It's a syntax error. You haven't declared T as a generic type argument

public string GetExpressionString<T>(Expression<Func<T, bool>> expr) where T: class
{
    return exp.Body.ToString();
}

notice the <T>



来源:https://stackoverflow.com/questions/17530852/expressionfunct-bool-method-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!