Use string value to create new instance

2019-04-12 13:04发布

I have a few classes: SomeClass1, SomeClass2.

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

Normally, I would do:

var someClass1 = new SomeClass1();

How can I create this instance from the following:

var className = "SomeClass1";

I am assuming I should use Type.GetType() or something but I can't figure it out.

Thanks.

3条回答
\"骚年 ilove
2楼-- · 2019-04-12 13:27
Assembly assembly = Assembly.LoadFrom("SomeDll.dll");    
var myinstance = assembly.CreateInstance("SomeNamespace.SomeClass1");
查看更多
小情绪 Triste *
3楼-- · 2019-04-12 13:32

Why not Dependency Injection frameworks?. This kinds of stuffs are greatly handled by dependency injection framework like Sprint.Net, Structure Map , NInject.....

查看更多
我命由我不由天
4楼-- · 2019-04-12 13:33

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

To get the type, first figure out what assembly it lives in. For the current assembly where your code is running, see Assembly.GetExecutingAssembly(). For all assemblies loaded in your current AppDomain, see AppDomain.CurrentDomain.GetAssemblies(). Otherwise, see Assembly.LoadFrom.

Then, if you have a class name but no namespace, you can enumerate the types in your assembly through Assembly.GetTypes().

Finally, create the type with 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());
        }
    }
}
查看更多
登录 后发表回答