【发布时间】: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