如何填充Activator.CreateInstance()方法创建的实例

时间:2014-11-27 21:30:03

标签: c# late-binding

class Program
{
    static void Main()
    {
        testclass tc = new testclass();
        Type tt = tc.GetType();
        Object testclassInstance = Activator.CreateInstance(tt);

        PropertyInfo prop = tt.GetProperty("name");

        MethodInfo MethodName = tt.GetMethod("set_" + prop.Name);
        string[] parameters = new string[2];

        parameters[0] = "first name of the bla bla";

        MethodName.Invoke(testclassInstance, parameters);

        Console.WriteLine(testclassInstance.GetType().GetProperty("name").GetValue(testclassInstance, null));

        Console.ReadLine();
    }
}

class testclass
{
    public string name { get; set; }
}

输出错误信息是:

  

参数计数不匹配

我不想为testclass创建构造函数并传递参数/ populate。我想逐个填充它的属性。

plz链接其他有用的实例填充方法。我知道这是最愚蠢的。

2 个答案:

答案 0 :(得分:3)

查看此问题:how to create an instance of class and set properties from a Bag object like session

Type myType = Type.GetType(className);
var instance = System.Activator.CreateInstance(myType);
PropertyInfo[] properties = myType.GetProperties();

foreach (var property in properties)
{
    if (property.CanWrite) 
    {
        property.SetValue(instance, session[property.Name], null);
    }
}

答案 1 :(得分:0)

这很简单:

prop.SetValue(testclassInstance, "first name of the bla bla");