Linq:将memberExpression类型转换为不可为空

时间:2009-11-25 16:19:07

标签: c# linq nullable

以下成员表达式类型有时可以是NUllable,我检查它,但是我需要将它转换为非可空类型,

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

有谁知道怎么做?

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:1)

这只是猜测,但您可以使用Nullable.GetValueOrDefault吗?我不确定返回类型是否正确。