我正在重写一些使用反射为 .NET Standard 1.4 编译的代码(目前针对 .NET 4.5.2。)。因此,我需要在许多地方对类型使用 GetTypeInfo()。
为了正确处理边缘情况,我的问题是,GetTypeInfo() 能否返回 null?文档 ( https://msdn.microsoft.com/en-us/library/system.reflection.introspectionextensions.gettypeinfo(v=vs.110).aspx) 对此没有提及。
当我从标准 .NET 4.5.2 项目打开 GetTypeInfo() 源时,我得到:
public static class IntrospectionExtensions
{
public static TypeInfo GetTypeInfo(this Type type){
if(type == null){
throw new ArgumentNullException("type");
}
var rcType=(IReflectableType)type;
if(rcType==null){
return null;
}else{
return rcType.GetTypeInfo();
}
}
}
这仍然令人困惑。当'(IReflectableType)type' 为null 时,有一个代码分支返回null,但为什么呢? - 之前针对 null 检查了 'type' 本身,当它为 null 时会抛出异常,因此我看不出 'rcType' 怎么可能为 null(请注意,这不是 'as' 运算符,它是直接类型转换)。
按照优良传统,IReflectableType.GetTypeInfo (, https://msdn.microsoft.com/en-us/library/system.reflection.ireflectabletype.gettypeinfo(v=vs.110).aspx) 上的文档也没有提及出现空结果的可能性。
使用反射的代码需要在很多地方使用 GetTypeInfo,如果允许 null 结果,则需要在每个这样的地方进行 null 检查和相应的操作。我已经检查了其他人的代码(包括 Microsoft 在 https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 中自己的示例),开发人员似乎将其视为不可能的空结果。对吗?
最佳答案
GetTypeInfo() 永远不会返回 null。
参见 new code在 .NET Core 中以及移植此代码的 Microsoft 人员留下的评论。
关于c# - GetTypeInfo 可以返回 null 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45955359/