【问题标题】:LINQ Expression conversion issueLINQ 表达式转换问题
【发布时间】:2015-02-27 17:27:19
【问题描述】:

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

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

【问题讨论】:

  • 各种类型是什么意思?喜欢接受通用而不是Project
  • 嗯,你的 func 正在返回字符串,但你试图返回 DateTime 或整数。期望的行为是什么?是否要事先将返回的属性转换为字符串?

标签: linq lambda expression-trees


【解决方案1】:

问题是您试图在生成string 的表达式中使用string 以外的类型的属性。没有转换是不允许的。

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

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

【讨论】:

  • 作为变体调用Convert.ToString 或类似的东西
猜你喜欢
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 2022-01-01
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多