如何从字符串表示形式创建类型的实例:
string scenario1 = "TheNamespace.MockScenario1";
Type theType = this.GetType().Assembly.GetType(scenario1);
var theInstance = (MockScenario1)Activator.CreateInstance(theType);
theInstance.GetInfo();
例如,如果您的类实现一个通用接口,那就更好了获取信息感知,然后你可以编写一个更通用的加载器:
var theInstance = (IGetInfoAware)Activator.CreateInstance(theType);
Note:您需要提供场景 1 和场景 2 的完整类名
See 激活器.CreateInstance https://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
EDIT:
正如 @Georg 指出的,如果类型未在上下文对象的程序集中声明,则必须首先获取托管该类型的程序集:
var theAssembly = (
from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()
where (assembly.FullName == "TheNamespace.AssemblyName")
select assembly
)
.FirstOrDefault();
if ( theAssembly!= null ){
Type theType = theAssembly.GetType(scenario1);
var theInstance = (IGetInfoAware)Activator.CreateInstance(theType);
theInstance.GetInfo();
}
如果由于某种原因您不知道程序集名称,则可以按如下方式解析类型:
public Type GetTypeFromString(String typeName)
{
foreach (Assembly theAssembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type theType = theAssembly.GetType(typeName);
if (theType != null)
{
return theType;
}
}
return null;
}