C#.NET - Type.GetType(“System.Windows.Forms.Form”) returns null

喜你入骨 提交于 2020-01-11 13:25:12

问题


I have a snippet of code in my application (which references System.Windows.Forms) which attempts to resolve type information for a Form class like so:

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

but Activator.CreateInstance fails because tForm is null.

How do I solve this?

EDIT: Types MUST be resolvable at runtime!


回答1:


You need to use assembly-qualified name of the type

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



回答2:


Check this Jon Skeet answer on this : 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

Note that if you're using a strongly named assembly (like Form in this case) you must include all the assembly information - versioning, public key token etc.




回答3:


Type.GetType(string) checks a few different things: if the string passed includes assembly information, then it will look there. Otherwise, the calling assembly and a few other system assemblies are checked (probably System and mscorlib). It does not check every assembly.

So, you have a few options:

  • include the assembly information in the string, i.e. "Namespace.TypeName, AssemblyName"
  • use assembly.GetType(string), where assembly is the correct assembly
  • manually loop over all the assemblies loaded in the current AppDomain, checking each in turn


来源:https://stackoverflow.com/questions/13048171/c-net-type-gettypesystem-windows-forms-form-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!