从文本名称实例化一个类 [英] Instantiate a class from its textual name

查看:208
本文介绍了从文本名称实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不要问我为什么,但我需要做到以下几点:

Don't ask me why but I need to do the following:

string ClassName = "SomeClassName";  
object o = MagicallyCreateInstance("SomeClassName");

我想知道有多少种方法做,这是和接近其方案中使用。

I want to know how many ways there are to do this is and which approach to use in which scenario.

例如:


  • Activator.CreateInstance

  • Assembly.GetExecutingAssembly.CreateInstance()

  • 任何其他的建议将是AP preciated

这问题并不意味着是一个开放式的讨论,因为我相信只有这么多的方法可以做到这一点。

This question is not meant to be an open ended discussion because I am sure there are only so many ways this can be achieved.

推荐答案

下面就是该方法可能看起来是这样的:

Here's what the method may look like:

private static object MagicallyCreateInstance(string className)
{
    var assembly = Assembly.GetExecutingAssembly();

    var type = assembly.GetTypes()
        .First(t => t.Name == className);

    return Activator.CreateInstance(type);
}

上面的code假定:

The code above assumes that:


  • 您正在寻找一类是在当前执行的程序集(这可以调整 - 只需更改组装来无论你需要)

  • 恰好有一个类你在一个组装查找名称

  • 类有一个默认的构造函数

  • you are looking for a class that is in the currently executing assembly (this can be adjusted - just change assembly to whatever you need)
  • there is exactly one class with the name you are looking for in that assembly
  • the class has a default constructor

更新:

下面是如何让所有从给定的类派生(在相同的程序集的定义)的类:

Here's how to get all the classes that derive from a given class (and are defined in the same assembly):

private static IEnumerable<Type> GetDerivedTypesFor(Type baseType)
{
    var assembly = Assembly.GetExecutingAssembly();

    return assembly.GetTypes()
        .Where(baseType.IsAssignableFrom)
        .Where(t => baseType != t);
}

这篇关于从文本名称实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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