[英]C# creating instance of class and set properties by name in string
我有问题 我想按名称创建类的实例。 我发现了Activator.CreateInstance
http://msdn.microsoft.com/zh-cn/library/d133hta4.aspx ,并且工作正常,我发现了这一点:我也通过使用字符串值进行反射来设置属性 。
但是如何同时做这件事? 我的意思是,我知道类的名称,我知道该类中的所有属性,并且都在字符串中。 例如:
string name = "MyClass";
string property = "PropertyInMyClass";
如何创建实例并为属性设置一些值?
您可以使用反射:
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
如果它在另一个程序集中,则jou必须在逗号后输入程序集名称(详细信息请参见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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.