c# - 如何区分 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.Nullable
1[System.Int32]类型的参数”
有没有办法在发送到表达式树之前检查类型?
我尝试检查 and 的类型,int
并且int?
两者都返回 true 以进行以下检查:
bool isIntNull = type == typeof(int?).GetType();
解决方案
为什么 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
推荐阅读
- php - sluggable 列如何注解@groups
- selenium - 如何使用 jQuery 获取开/关切换按钮的值?
- php - 如何修复我的代码的漏洞?
- java - Java-Android Toast 消息没有向我显示消息
- javascript - 在正确结果之上返回未定义的反应函数
- r - R:根据列内容有条件地提取列名
- xamarin - Xamarin 表单 - Navigation.PopAsync() 不起作用
- webpack - localhost webpack 显示的文件目录?
- r - r 创建与另一列分组的行元素匹配的新数据框
- javascript - React Native - 如何从 ScrollView 获取视图的 Y 偏移值?