LINQ表达式转换问题

时间:2015-02-27 17:27:19

标签: linq lambda expression-trees

我正在尝试找到如何使其适用于各种类型。 在此先感谢您的帮助!

public static void Main()
{
    GetKeySelector("String01");     // OK
    GetKeySelector("Date01");       // ArgumentException: Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type 'System.String'
    GetKeySelector("Integer01");    // ArgumentException: Expression of type 'System.Int32' cannot be used for return type 'System.String'
}


private static Expression<Func<Project,string>> GetKeySelector(string propertyName)

{    
   var paramExpr = Expression.Parameter(typeof (Project), "p");
   var property = Expression.Property(paramExpr, propertyName);  
   var finalLambda = Expression.Lambda<Func<Project, string>>(property, paramExpr);
   return finalLambda;
}

class Project
{
    public DateTime? Date01 {get;set;}  
    public int Integer01 {get;set;}     
    public string String01 {get;set;} 
}

1 个答案:

答案 0 :(得分:0)

问题是您尝试在生成string的表达式中使用string以外的类型的属性。如果没有转换,则不允许这样做。

解决此问题的一种方法是更改​​代码以生成object而不是string s,如下所示:

private static Expression<Func<Project,object>> GetKeySelector(string propertyName) {    
    var paramExpr = Expression.Parameter(typeof (Project), "p");
    var property = Expression.Property(paramExpr, propertyName); 
    var cast = Expression.Convert(property, typeof(object));
    return Expression.Lambda<Func<Project,object>>(cast, paramExpr);
}

或者,您可以通过表达式调用Convert.ToString