LINQ表达式转换问题
我正试图找到如何使这与各种类型的工作。 提前感谢您的帮助LINQ表达式转换问题,linq,lambda,expression-trees,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 'Syste
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;}
}
publicstaticvoidmain()
{
GetKeySelector(“String01”);//确定
GetKeySelector(“Date01”);//ArgumentException:类型为“System.Nullable`1[System.DateTime]”的表达式不能用于返回类型“System.String”
GetKeySelector(“Integer01”);//ArgumentException:类型为“System.Int32”的表达式不能用于返回类型“System.String”
}
私有静态表达式GetKeySelector(字符串propertyName)
{
var paramExpr=Expression.Parameter(typeof(Project),“p”);
var property=Expression.property(paramExpr,propertyName);
var finalLambda=Expression.Lambda(属性,参数xpr);
返回finalLambda;
}
班级项目
{
公共日期时间?日期01{get;set;}
公共整数01{get;set;}
公共字符串String01{get;set;}
}
问题在于,您试图在生成字符串的表达式中使用类型不同于字符串的属性。未经转换,这是不允许的
解决此问题的一种方法是将代码更改为生成对象
s,而不是字符串
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);
}
私有静态表达式GetKeySelector(string propertyName){
var paramExpr=Expression.Parameter(typeof(Project),“p”);
var property=Expression.property(paramExpr,propertyName);
var cast=Expression.Convert(属性,typeof(对象));
返回表达式.Lambda(cast,paramExpr);
}
或者,您可以通过表达式调用Convert.ToString
。各种类型是什么意思?就像接受一个泛型而不是项目
?嗯,您的func返回字符串,但您试图返回DateTime或整数。期望的行为是什么?是否要先将返回的属性转换为字符串?作为变量调用convert.ToString
或类似的内容