使用字符串值来创建新实例 [英] Use string value to create new instance

查看:135
本文介绍了使用字符串值来创建新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类别:SomeClass1,SomeClass2

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?

通常情况下,我会做:

var someClass1 = new SomeClass1();

我如何可以从下面创建此实例:

How can I create this instance from the following:

var className = "SomeClass1";

我假设我应该使用Type.GetType()或东西,但我不明白。

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

感谢。

推荐答案

首先,你需要通过的反射,然后你可以用的 激活

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

要获取类型,首先弄清楚什么是汇编它生活在对于在您的code运行当前程序集,看到的 Assembly.GetExecutingAssembly() 。对于当前的AppDomain中加载的所有组件,请参见 AppDomain.CurrentDomain.GetAssemblies() 。否则,请参阅 Assembly.LoadFrom

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.

然后,如果你有一个类的名字,但没有命名空间,您可以在装配通过的 Assembly.GetTypes()

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

最后,创建 类型Activator.CreateInstance

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());
        }
    }
}

这篇关于使用字符串值来创建新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆