C# 从其文本名称实例化一个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9854900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Instantiate a class from its textual name
提问by Raheel Khan
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.
我想知道有多少种方法可以做到这一点,以及在哪种情况下使用哪种方法。
Examples:
例子:
Activator.CreateInstanceAssembly.GetExecutingAssembly.CreateInstance("")- Any other suggestions would be appreciated
Activator.CreateInstanceAssembly.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.
这个问题并不意味着是一个开放式的讨论,因为我相信只有这么多方法可以实现。
采纳答案by Cristian Lupascu
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);
}
The code above assumes that:
上面的代码假设:
- you are looking for a class that is in the currently executing assembly (this can be adjusted - just change
assemblyto whatever you need) - there is exactly one class with the name you are looking for in that assembly
- the class has a default constructor
- 您正在寻找当前正在执行的程序集中的类(可以调整 - 只需更改
assembly为您需要的任何内容) - 在该程序集中,只有一个类与您要查找的名称同名
- 该类有一个默认构造函数
Update:
更新:
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);
}
回答by Balazs Tihanyi
Activator.CreateInstance(Type.GetType("SomeNamespace.SomeClassName"));
or
或者
Activator.CreateInstance(null, "SomeNamespace.SomeClassName").Unwrap();
There are also overloads where you can specify constructor arguments.
还有重载,您可以在其中指定构造函数参数。

