gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:34:52 28 4
gpt4 key购买 nike

以下成员表达式类型有时可以为 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com