【问题标题】:Type.GetType("System.Net.WebException") returns null [duplicate]Type.GetType("System.Net.WebException") 返回 null [重复]
【发布时间】:2019-11-23 08:57:23
【问题描述】:

我正在尝试通过执行以下操作从其名称中获取对 System.Net.WebException 的类型引用:

var t = Type.GetType("System.Net.WebException");

t 是 null,我不明白为什么。我的项目是一个面向 .NET 4.6.1 的类库。我正在引用 System 并且还尝试引用 System.Net 和 System.Web 没有任何运气。

以下编译并返回正确的类型:

var t = typeof(System.Net.WebException);

但我需要string 版本才能在这里工作。我也试过这个:

var t = Type.GetType("System.Net.WebException, System");

也返回null。

有什么想法吗?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    根据Type.GetType的docs,如果类型在mscorlib.dll中,则只能传递命名空间限定的类型名称,否则必须使用程序集限定的名称。 WebException 不在 mscorlib.dll 中,所以你至少需要:

    Type.GetType("System.Net.WebException, System, Version=4.0.0.0")
    

    通过检查typeof(WebException).AssemblyQualifiedName,您可以看到类似于:

    System.Net.WebException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    

    【讨论】:

      【解决方案2】:

      你应该使用这个:

      var t = Type.GetType("System.Net.WebException" + ", System");
      

      您是否尝试过以下方法:

       var t = Type.GetType("System.Net.WebException", true);
      

      您会收到以下错误消息:

      未处理的异常。 System.TypeLoadException:无法加载类型 来自程序集“ConsoleApp1,版本=1.0.0.0”的“System.Net.WebException”, 文化=中性,PublicKeyToken=null'。在 System.RuntimeTypeHandle.GetTypeByName(字符串名称,布尔值 ......

      我们传递的第二个参数true 表示如果找不到类型,我们希望此方法调用抛出错误。所以通过这个,你会注意到Type.GetType 需要完全限定的名称。更正式的说法是here:

      public static Type GetType (string typeName);
      

      参数

      typeName String
      

      要获取的类型的程序集限定名称。请参阅 AssemblyQualifiedName。 如果该类型在当前执行的程序集中或在 Mscorlib.dll 中,则提供由其命名空间限定的类型名称就足够了。

      【讨论】:

      • 你的回答是正确的。我接受了另一个答案,因为它更精确(IMO)。我试过"System.Net.WebException" + ", System"(我问题的最后一部分)。添加 throwOnError 布尔值的好处。
      • @ThomasArdal 根本不是问题 :) 并且无需解释您的选择 :)。谢谢!
      猜你喜欢
      • 2012-02-01
      • 2011-11-09
      • 1970-01-01
      • 2019-11-09
      • 2011-11-18
      • 1970-01-01
      • 2012-10-14
      相关资源
      最近更新 更多