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

时间:2012-08-14 18:49:03

标签: c# reflection

我有一些问题。我想按名称创建类的实例。 我找到了Activator.CreateInstance http://msdn.microsoft.com/en-us/library/d133hta4.aspx,它运行正常,我发现了这个: Setting a property by reflection with a string value

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

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

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

3 个答案:

答案 0 :(得分:52)

您可以使用反射:

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);
    }
}

答案 1 :(得分:2)

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

要使用方法Type.GetType,您必须输入程序集限定名称。 这与项目名称有关例如: GenerateClassDynamically_ConsoleApp1.Foo

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

答案 2 :(得分:-3)

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);
}