get property lambda from property Name (Where property type can be nullable)
Hi there I basically need a function with the following signature
Expression<Func<T, object>> GetPropertyLambda(开发者_开发问答string propertyName)
I have made a few attempts but the problem arise when the property is nullable
it goes something like thisParameterExpression param = Expression.Parameter(typeof(T), "arg");
Expression member = Expression.Property(param, propertyName);
//this next section does conver if the type is wrong however
// when we get to Expression.Lambda it throws
Type typeIfNullable = Nullable.GetUnderlyingType(member.Type);
if (typeIfNullable != null)
{
member = Expression.Convert(member, typeIfNullable);
}
return Expression.Lambda<Func<T, object>>(member, param);
The Exception is
Expression of type 'System.Decimal' cannot be used for return type 'System.Object'
I would really apreciate some ideas and also why this doesnt work as expected
Thanks
Actually I don't think the problem has anything to do with Nullable types, but rather with value types. Try your method with a property of type decimal
(not Nullable<decimal>
) : it will fail the same way.
Have a look at how expression trees are generated for value and reference types (using LinqPad for instance)
Expression<Func<T, object>> lambda = x => x.AString;
(reference type)
=> The body is aMemberExpression
Expression<Func<T, object>> lambda = x => x.ADecimal;
(value type)
=> The body is aUnaryExpression
withNodeType = Convert
andType = typeof(object)
, and itsOperand
is aMemberExpression
I modified your method slightly to take that into account, and it seems to work fine :
ParameterExpression param = Expression.Parameter(typeof(T), "arg");
Expression member = Expression.Property(param, propertyName);
if (member.Type.IsValueType)
{
member = Expression.Convert(member, typeof(object));
}
return Expression.Lambda<Func<T, object>>(member, param);
精彩评论