【问题标题】:Expression<Func<T, bool>> method argument表达式<Func<T, bool>> 方法参数
【发布时间】:2013-07-08 15:49:06
【问题描述】:

我正在尝试创建一个返回表达式的字符串版本的通用方法:

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

Cannot resolve symbol T

如果我将 T 更改为硬编码类型,效果会很好。

我错过了什么?

【问题讨论】:

    标签: c# asp.net generics delegates expression


    【解决方案1】:

    您需要将T 声明为方法的泛型类型参数:

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

    进一步阅读:

    【讨论】:

      【解决方案2】:

      这是一个语法错误。您尚未将 T 声明为泛型类型参数

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

      注意&lt;T&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-02
        • 1970-01-01
        相关资源
        最近更新 更多