【问题标题】:how to populate an instance created by Activator.CreateInstance() method [duplicate]如何填充由 Activator.CreateInstance() 方法创建的实例 [重复]
【发布时间】:2015-01-26 12:51:36
【问题描述】:
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 创建构造函数并像那样传递参数/填充。我想一一填充它的属性。

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

【问题讨论】:

标签: c# late-binding


【解决方案1】:

看看这个问题: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);
    }
}

【讨论】:

  • 不要忘记在调用property.SetValue之前添加if (property.CanWrite),以防有些属性没有setter。
  • 谢谢@Koresh,我已经更新了答案:)
【解决方案2】:

这很简单:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-14
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多