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

标签 c# linq nullable

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

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

有人知道吗?

最佳答案

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

关于c# - Linq:将 memberExpression 类型转换为不可空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1798085/

相关文章:

java - @Nullable 似乎不适用于 @AssistedInject

c# - Nullable 可以用作 C# 中的仿函数吗?

c# - ASP.Net Core 中的全局异常处理程序(非 UI)

c# - 从缓存列表查询 IQuery 返回 null 异常

c# - C# 中的 Microsoft.Office.Interop.Word 的 SynonymInfo[]

sql - Entity Framework 中的空间连接

c# - 分组同类对象 C#

java - 是否需要覆盖注解 - Kotlin

c# - XAML 绑定(bind)到另一个元素的对立面

c# - HtmlHelper 扩展的动态