您可以使用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