Skip to main content
 首页 » 编程设计

c#之如何在我的程序中使用 .NET 类型字符串

2024年02月24日41jpfss

例如,在 .NET app.config 中,您可能会得到

<configuration> 
   <configSections> 
      <section name="MyConfig" type="MyAssembly.MyType, MyAssembly, PublicKeyToken=null" /> 
   </configSections> 
   ... 
</configuration> 

类型部分中的签名似乎在各种 .NET 地方都已标准化,但我不知道如何在我自己的程序中执行此操作。我在我的程序中使用了 System.Activator,但这感觉就像我在重复 .NET 已经完成的工作。

在编程方面,我该怎么做:

void Main() 
{ 
   object instance = CreateInstance("MyAssembly.MyType, MyAssembly, PublicKeyToken=null"); 
   Console.WriteLine(instance.GetType().Name); 
} 
 
object CreateInstance(string dotNetTypeSignature) 
{ 
   // Code goes here. 
} 

请您参考如下方法:

您可以调用Type.GetType method获取具有给定(程序集限定)名称的 Type 对象。

您可以调用Activator.CreateInstance method创建类型的实例。 (假设该类型有一个公共(public)默认构造函数,或者您知道它需要哪些构造函数参数)。

例如:

Activator.CreateInstance(Type.GetType(name));