2009-11-25 68 views
2

以下成員表達式類型有時是空的,我米檢查,但是我需要將其轉換爲非可空類型,的Linq:變換memberExpression類型不可空

MemberExpression member = Expression.Property(param, something); 
var membertype = member.Type; 
if (membertype.IsGenericType && membertype.GetGenericTypeDefinition() == typeof(Nullable<>)) 
     { // convert to not nullable type?... 

有誰知道怎麼樣?

回答

9

您可以使用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 });  
    } 
} 
+0

不錯,正在尋找類似的東西:) – Shawn 2009-11-25 18:47:59

+0

有點晚了,但這正是我現在解決的一個問題;謝謝! – 2014-02-13 13:52:36

1

這只是一個猜測,但可以使用Nullable.GetValueOrDefault嗎?我不確定返回類型是否正確。

+0

您好,感謝回答,我需要將會員轉換爲基本會員,但這不是一個可空的類型,實際上並不需要值 – roundcrisis 2009-11-25 16:48:31

+0

啊好吧,不知道你必須這樣使用它,謝謝 – roundcrisis 2009-11-25 16:57:03