How to get instance of a class given the class name?

前端 未结 2 541
情歌与酒
情歌与酒 2021-01-19 04:03

I\'ve seen this Topic : Creating an instance from a class name

and written this code:

public partial class Form1 : Form
{
    public Form1()
    {
           


        
2条回答
  •  梦谈多话
    2021-01-19 04:35

    According to MSDN null actually doesn't mean current assembly. It means that assembly will be searched (its matter when your class is located in another assembly). Also you need specify not only the class name. So, to prevent searching and get type correctly you need to write full assembly-qualified name:

    Type objType = Type.GetType("YourNamespace.MyClass, YourAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
    object obj = Activator.CreateInstance(objType);
    MyClass t = (MyClass)obj;
    

    Assembly-qualified name you can retrieve for example with next code (to check that you are not mistaken):

    string name = typeof(MyClass).AssemblyQualifiedName;
    

提交回复
热议问题