28

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

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

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

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

4

3 回答 3

69

你可以使用反射:

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);
    }
}
于 2012-08-14T18:52:18.140 回答
3

如果你有 System.TypeLoad 异常,你的类名是错误的。

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

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

于 2016-03-16T22:28:43.070 回答
-4
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);
}
于 2016-03-27T14:29:39.157 回答