如何区分 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] ”类型的参数

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

我尝试检查和的类型,int并且int?对于以下检查都返回 true:

bool isIntNull = type == typeof(int?).GetType();
D斯坦利

为什么 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章