Subclass under string na C #

I have a class and a subclass

namespace MyCode
{
    public class Class1
    {
        int a = 1;
        int b = 2;
        public class SubClass1
        {
            int a = 1;
            int b = 2;
        }
    }
}

Now I need to instantiate each class by the name of the string. I can do this from a class, but not for a subclass.

It works:

var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1"));

But this does not work:

var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1.SubClass1"));

What do I need to do for the second option?

+4
source share
2 answers

Whenever you do not know what name should be, you can see the name by checking typeof(MyCode.Class1.SubClass1).FullName.

If you have a subclass, you use a sign +.

var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1+SubClass1"));
+8
source
var myObj = Activator.CreateInstance(Type.GetType("MyCode.Class1+SubClass1"));

Its +when working with nested types, not.

+6
source

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


All Articles