从其文本名称实例化一个类 [英] Instantiate a class from its textual name
本文介绍了从其文本名称实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不要问我为什么,但我需要做以下事情:
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("")
- 如有任何其他建议,我们将不胜感激
这个问题并不是一个开放式的讨论,因为我相信只有这么多方法可以实现.
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.
推荐答案
以下是该方法的外观:
private static object MagicallyCreateInstance(string className)
{
var assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetTypes()
.First(t => t.Name == className);
return Activator.CreateInstance(type);
}
上面的代码假设:
- 您正在寻找当前正在执行的程序集中的类(这可以调整 - 只需将
assembly
更改为您需要的任何内容) - 在该程序集中只有一个类与您要查找的名称相同
- 该类有一个默认构造函数
- 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屋!
查看全文