How to get an instance of a class with the class name?

I saw this topic: Creating an instance from a class name

and wrote this code:

public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { object obj = Activator.CreateInstance(null, "MyClass"); MyClass t = (MyClass)obj; t.My1 = 100; MessageBox.Show(t.My1.ToString()); } } public class MyClass { public int My1 { get; set; } public int My2 { get; set; } } 

However, when there is an exception in his runs:

 Could not load type 'MyClass' from assembly 'Test_Reflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. 

I have another question. I have a class in one assembly that has a property. In another assembly, I want to instantiate this object and access its properties by typing one of them, just using the stringy Class Name. How can i do this?

+4
source share
2 answers

According to MSDN, null does not actually mean the current build. This means that the assembly will be checked (its a question when your class is in another assembly). Also you need to specify not only the class name. Thus, to prevent the search and get the type correctly, you need to write the full name assigned to the assembly :

 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; 

The assembly name, which you can get, for example, using the following code (to make sure that you are not mistaken):

 string name = typeof(MyClass).AssemblyQualifiedName; 
+10
source

You just need to add the namespace to the class name. In exe console project this works for me. You had a problem with how you used the handle of the returned object. This is not an object, but an ObjectHandle, and you need to call Unwrap () to get 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, "CSharpConsoleTests.MyClass"); var t = (MyClass)obj.Unwrap(); t.My1 = 100; MessageBox.Show(t.My1.ToString()); } } } 
0
source

Source: https://habr.com/ru/post/1343437/


All Articles