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

前端 未结 2 523
情歌与酒
情歌与酒 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;
    
    0 讨论(0)
  • 2021-01-19 04:38

    You just need to prepend the namespace to the class name. In a console exe project, this works for me. You did have a problem with the way you were using the returned object handle. It's not an Object, but an ObjectHandle and you need to call Unwrap() get at the actual type instance.

    namespace CSharpConsoleTest
    {
        public class MyClass
        {
            public int My1 { get; set; }
            public int My2 { get; set; }
        }
    
        public class Program
        {
            public static void Main(string[] args)
            {
                var obj = Activator.CreateInstance(null, "CSharpConsoleTest.MyClass");
    
                var t = (MyClass)obj.Unwrap();
                t.My1 = 100;
                MessageBox.Show(t.My1.ToString());
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题