【问题标题】:Linq: transform memberExpression type to not nullableLinq:将 memberExpression 类型转换为不可为空
【发布时间】:2009-11-25 16:19:06
【问题描述】:

以下成员表达式类型有时可以为 NULL,我正在检查,但是我需要将其转换为不可为空的类型,

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

有人知道怎么做吗?

【问题讨论】:

    标签: c# linq nullable


    【解决方案1】:

    您可以使用Nullable.GetUnderlyingType 来检查(更简单的)Nullable&lt;T&gt;,并且只需使用GetValueOrDefault - 如下所示(我只包含Func&lt;Foo,int&gt; 等作为演示):

    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 });    
        }
    }
    

    【讨论】:

    • 不错,正在寻找类似的东西:)
    • 有点晚了,但这正是我现在解决问题的方法;谢谢!
    【解决方案2】:

    这只是一个猜测,但你能使用 Nullable.GetValueOrDefault 吗?我不确定返回类型是否正确。

    【讨论】:

    • 您好,感谢您的回答,我需要将成员转换为基本成员,但这不是可空类型,实际上不需要该值
    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2019-07-18
    • 2017-01-11
    • 2022-09-30
    • 2012-04-21
    • 2019-12-03
    • 1970-01-01
    • 2017-05-04
    相关资源
    最近更新 更多