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