[英]C# creating instance of class and set properties by name in string
I have some problem. 我有问题 I want to creating instance of class by name.
我想按名称创建类的实例。 I found
Activator.CreateInstance
http://msdn.microsoft.com/en-us/library/d133hta4.aspx and it works fine, and I found this: Setting a property by reflection with a string value too. 我发现了
Activator.CreateInstance
http://msdn.microsoft.com/zh-cn/library/d133hta4.aspx ,并且工作正常,我发现了这一点:我也通过使用字符串值进行反射来设置属性 。
But how to do both od this? 但是如何同时做这件事? I mean, I know the name of class, I know all properties in that class and I have this in string.
我的意思是,我知道类的名称,我知道该类中的所有属性,并且都在字符串中。 For example:
例如:
string name = "MyClass";
string property = "PropertyInMyClass";
How to create instance and set some value to properties ? 如何创建实例并为属性设置一些值?
You could use 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);
}
}
If you had System.TypeLoad Exception, your class name is wrong. 如果您有System.TypeLoad Exception,则您的类名错误。
To method Type.GetType you must enter assembly-qualified name . 对于Type.GetType方法,必须输入程序集限定名称 。 That is with the project name For example: GenerateClassDynamically_ConsoleApp1.Foo
那就是项目名称,例如: GenerateClassDynamically_ConsoleApp1.Foo
If it is in another assembly jou must enter assembly name after comma (details on https://stackoverflow.com/a/3512351/1540350 ): Type.GetType("GenerateClassDynamically_ConsoleApp1.Foo,GenerateClassDynamically_ConsoleApp1"); 如果它在另一个程序集中,则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.