您可以使用Nullable.GetUnderlyingType
检查(更简单)为Nullable<T>
,并且只使用GetValueOrDefault
- 像下面(我只包括了Func<Foo,int>
等为演示):
using System;
using System.Linq.Expressions;
class Foo {
public int? Bar { get; set; }
static void Main() {
var param = Expression.Parameter(typeof(Foo), "foo");
Expression member = Expression.PropertyOrField(param, "Bar");
Type typeIfNullable = Nullable.GetUnderlyingType(member.Type);
if (typeIfNullable != null) {
member = Expression.Call(member,"GetValueOrDefault",Type.EmptyTypes);
}
var body = Expression.Lambda<Func<Foo, int>>(member, param);
var func = body.Compile();
int result1 = func(new Foo { Bar = 123 }),
result2 = func(new Foo { Bar = null });
}
}
不错,正在寻找类似的东西:) – Shawn 2009-11-25 18:47:59
有点晚了,但这正是我现在解决的一个问题;谢谢! – 2014-02-13 13:52:36