【问题标题】:C#.NET - Type.GetType("System.Windows.Forms.Form") returns nullC#.NET - Type.GetType("System.Windows.Forms.Form") 返回 null
【发布时间】:2012-10-14 10:21:20
【问题描述】:

我的应用程序中有一段代码(引用 System.Windows.Forms),它尝试解析 Form 类的类型信息,如下所示:

Type tForm = Type.GetType("System.Windows.Forms.Form");
dynamic instance = Activator.CreateInstance(tForm);

但Activator.CreateInstance 失败,因为tForm 为空。

我该如何解决这个问题?

编辑:类型必须在运行时可解析!

【问题讨论】:

  • 当前程序集的项目是否有对 System.Windows.Forms 的引用? (如果您使用的是多项目解决方案)
  • 为什么不只是typeof(System.Windows.Forms.Form)?
  • AppDomain.CurrentDomain.GetAssemblies() 是否显示 System.Windows.Forms 已加载?
  • @Jodrell 因为类型信息正在运行时解析
  • @activwerx,或者,在这种情况下,类型信息在运行时没有被解析。我实际上的意思是为什么要动态地这样做?

标签: c# .net reflection types


【解决方案1】:

您需要使用类型的程序集限定名称

Type tForm = Type.GetType("System.Windows.Forms.Form, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

【讨论】:

  • Pranay Rana,我回滚了你的编辑,因为语法突出显示不佳
【解决方案2】:

Type.GetType(string) 检查几个不同的东西:如果传递的字符串包括程序集信息,那么它会在那里查找。否则,将检查调用程序集和一些其他系统程序集(可能是 System 和 mscorlib)。它不检查每个程序集。

所以,你有几个选择:

  • 在字符串中包含汇编信息,即"Namespace.TypeName, AssemblyName"
  • 使用assembly.GetType(string),其中assembly 是正确的程序集
  • 手动循环当前AppDomain中加载的所有程序集,依次检查每个程序

【讨论】:

    【解决方案3】:

    检查这个 Jon Skeet 的答案:https://stackoverflow.com/a/3758295/314488

    using System;
    using System.Windows.Forms;
    
    class Test
    {
        static void Main()
        {
            string name = typeof(Form).AssemblyQualifiedName;
            Console.WriteLine(name);
    
            Type type = Type.GetType(name);
            Console.WriteLine(type);
        }
    }
    Output:
    
    System.Windows.Forms.Form, System.Windows.Forms, Version=4.0.0.0, Culture=neutral,
    PublicKeyToken=b77a5c561934e089
    System.Windows.Forms.Form
    

    请注意,如果您使用的是强命名程序集(如本例中的 Form),则必须包含所有程序集信息 - 版本控制、公钥令牌等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-09
      • 2012-02-01
      • 2011-11-18
      • 2011-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多