C#创建类的实例并按字符串中的名称设置属性

我有一些问题。 我想按名称创建类的实例。 我找到了Activator.CreateInstance http://msdn.microsoft.com/en-us/library/d133hta4.aspx并且它工作正常,我发现了这一点: 通过reflection设置一个属性也是一个字符串值 。

但是这两个怎么办呢? 我的意思是,我知道类的名称,我知道该类中的所有属性,我在字符串中有这个。 例如:

 string name = "MyClass"; string property = "PropertyInMyClass"; 

如何创建实例并为属性设置一些值?

你可以使用Reflection:

 using System; using System.Reflection; public class Foo { public string Bar { get; set; } } public class Program { static void Main() { string name = "Foo"; string property = "Bar"; string value = "Baz"; // Get the type contained in the name string Type type = Type.GetType(name, true); // create an instance of that type object instance = Activator.CreateInstance(type); // Get a property on the type that is stored in the // property string PropertyInfo prop = type.GetProperty(property); // Set the value of the given property on the given instance prop.SetValue(instance, value, null); // at this stage instance.Bar will equal to the value Console.WriteLine(((Foo)instance).Bar); } } 

如果您有System.TypeLoad Exception,则您的类名是错误的。

对于方法Type.GetType,您必须输入程序集限定名称 。 这是项目名称例如: GenerateClassDynamically_ConsoleApp1.Foo

如果它在另一个程序集中,则必须在逗号后输入程序集名称( https://stackoverflow.com/a/3512351/1540350上的详细信息): Type.GetType(“GenerateClassDynamically_ConsoleApp1.Foo,GenerateClassDynamically_ConsoleApp1”);

 Type tp = Type.GetType(Namespace.class + "," + n.Attributes["ProductName"].Value + ",Version=" + n.Attributes["ProductVersion"].Value + ", Culture=neutral, PublicKeyToken=null"); if (tp != null) { object o = Activator.CreateInstance(tp); Control x = (Control)o; panel1.Controls.Add(x); }