GetTypeInfo可以返回null吗?

Zby*_*ekZ 6 .net c# .net-standard

我正在重写一些代码(目前针对.NET 4.5.2.),它使用反射来编译.NET Standard 1.4.因此,我需要在许多地方对Type使用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();
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

这仍然令人困惑.当'(IReflectableType)类型为null时,有一个代码分支返回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,如果允许null结果,则需要在每个这样的地方进行空检查和相应的操作.我检查了其他人的代码(包括微软自己的例子,地址是https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396并且开发人员似乎将其视为无效结果.那是对的吗?

Kos*_*tya 3

GetTypeInfo() 永远不应该返回 null。

请参阅.NET Core 中的新代码以及移植此代码的 Microsoft 人员留下的评论。