如何在C#中区分typeof(int)== typeof(int?)

Bry*_*ump 0 c#

为什么C#设置相同?

typeof(int).GetType() == typeof(int?).GetType()
Run Code Online (Sandbox Code Playgroud)

在编写表达式树时,会出现问题

List<int?> ids = JsonConvert.DeserializeObject<List<int?>>(filter.Value?.ToString());
var filterField = filter.PropertyName;
var method = ids.GetType().GetMethod("Contains");
return Expression.Call(Expression.Constant(ids), method, member);
Run Code Online (Sandbox Code Playgroud)

生成此错误

System.ArgumentException:类型'System.Int32'的表达式不能用于'System.Nullable 1[System.Int32]' of method 'Boolean Contains(System.Nullable1 [System.Int32] 类型的参数

有没有办法在发送到表达式树之前检查类型?

我尝试检查类型int和,int?并且两者都返回true以进行以下检查:

bool isIntNull = type == typeof(int?).GetType();
Run Code Online (Sandbox Code Playgroud)

D S*_*ley 10

为什么C#设置相同?

因为他们是平等的.

typeof(int)RuntimeType由编译器生成实例

typeof(int?)编译器生成不同的 RuntimeType实例

调用GetType()任何RuntimeType实例都会返回该类型System.RuntimeType

我想你想要的

typeof(int) == typeof(int?)
Run Code Online (Sandbox Code Playgroud)

bool isIntNull = type.Equals(typeof(int?));
Run Code Online (Sandbox Code Playgroud)

证明:

Console.WriteLine(typeof(int));
Console.WriteLine(typeof(int?));
Console.WriteLine(typeof(int).GetType());
Console.WriteLine(typeof(int?).GetType());
Run Code Online (Sandbox Code Playgroud)

输出:

System.Int32
System.Nullable`1[System.Int32]
System.RuntimeType
System.RuntimeType
Run Code Online (Sandbox Code Playgroud)