GetTypeInfo 可以 return 为空吗?
Can GetTypeInfo ever return null?
我正在重写一些使用反射为 .NET Standard 1.4 编译的代码(目前针对 .NET 4.5.2。)。因此,我需要在许多地方对类型使用 GetTypeInfo()。
为了正确处理边缘情况,我的问题是,GetTypeInfo() 是否可以 return 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 时,有一个代码分支returns null,但为什么呢? - 之前检查 'type' 本身是否为 null,当它为 null 时会抛出异常,因此我看不出 'rcType' 怎么可能为 null(请注意,这不是 'as' 运算符,它是直接类型转换)。
按照优良传统,IReflectableType.GetTypeInfo(,https://msdn.microsoft.com/en-us/library/system.reflection.ireflectabletype.gettypeinfo(v=vs.110).aspx)上的文档也没有提及出现无效结果的可能性。
使用反射的代码需要在很多地方使用GetTypeInfo,如果允许空结果,则需要在每个这样的地方进行空检查和相应的操作。我检查了其他人的代码(包括微软自己在 https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 的示例),开发人员似乎将其视为不可能的空结果。对吗?
GetTypeInfo() 永远不应该 return null。
查看.NET Core中的new code以及移植此代码的微软人留下的评论。
我正在重写一些使用反射为 .NET Standard 1.4 编译的代码(目前针对 .NET 4.5.2。)。因此,我需要在许多地方对类型使用 GetTypeInfo()。
为了正确处理边缘情况,我的问题是,GetTypeInfo() 是否可以 return 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 时,有一个代码分支returns null,但为什么呢? - 之前检查 'type' 本身是否为 null,当它为 null 时会抛出异常,因此我看不出 'rcType' 怎么可能为 null(请注意,这不是 'as' 运算符,它是直接类型转换)。
按照优良传统,IReflectableType.GetTypeInfo(,https://msdn.microsoft.com/en-us/library/system.reflection.ireflectabletype.gettypeinfo(v=vs.110).aspx)上的文档也没有提及出现无效结果的可能性。
使用反射的代码需要在很多地方使用GetTypeInfo,如果允许空结果,则需要在每个这样的地方进行空检查和相应的操作。我检查了其他人的代码(包括微软自己在 https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 的示例),开发人员似乎将其视为不可能的空结果。对吗?
GetTypeInfo() 永远不应该 return null。
查看.NET Core中的new code以及移植此代码的微软人留下的评论。