首页 > 解决方案 > 如何区分 C# 中 typeof(int) == typeof(int?)

问题描述

为什么 C# 将它们设置为相等?

typeof(int).GetType() == typeof(int?).GetType()

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

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

生成此错误

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

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

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

bool isIntNull = type == typeof(int?).GetType();

标签: c#

解决方案


为什么 C# 将它们设置为相等?

因为他们是平等的。

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

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

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

我想你想要

typeof(int) == typeof(int?)

bool isIntNull = type.Equals(typeof(int?));

证明:

Console.WriteLine(typeof(int));
Console.WriteLine(typeof(int?));
Console.WriteLine(typeof(int).GetType());
Console.WriteLine(typeof(int?).GetType());

输出:

System.Int32
System.Nullable`1[System.Int32]
System.RuntimeType
System.RuntimeType

推荐阅读