Use string value to create a new instance

I have several classes: SomeClass1, SomeClass2.

How to create a new instance of one of these classes using the class name from a string?

Normally I would do:

var someClass1 = new SomeClass1();

How to create this instance from the following:

var className = "SomeClass1";

I suppose I should use Type.GetType () or something, but I cannot figure it out.

Thank.

+3
source share
3 answers

First you need to get the reflection type , and then you can create it with Activator.

, , . , , . Assembly.GetExecutingAssembly(). , AppDomain, . AppDomain.CurrentDomain.GetAssemblies(). . Assembly.LoadFrom.

, , , Assembly.GetTypes().

, Activator.CreateInstance.

using System;
using System.Linq;
using System.Reflection;

namespace ReflectionTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly thisAssembly = Assembly.GetExecutingAssembly();
            Type typeToCreate = thisAssembly.GetTypes().Where(t => t.Name == "Program").First();

            object myProgram = Activator.CreateInstance(typeToCreate);

            Console.WriteLine(myProgram.ToString());
        }
    }
}
+2
Assembly assembly = Assembly.LoadFrom("SomeDll.dll");    
var myinstance = assembly.CreateInstance("SomeNamespace.SomeClass1");
+4

Why not the basics for injection? These types of materials are largely handled by dependency injection infrastructure such as Sprint.Net, Structure Map, NInject .....

0
source

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


All Articles