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

标签 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; }
}

输出错误信息为:

Parameter count mismatch

我不想为测试类创建构造函数并像这样传递参数/填充。我想一一填充它的属性。

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

最佳答案

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

关于c# - 如何填充由 Activator.CreateInstance() 方法创建的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27178880/

相关文章:

c# - 为客户端 Blazor 部署环境动态配置 Http.BaseAddress

c# - 有什么方法可以覆盖 MVC Controller 操作吗?

当在派生类中定义重载时,C# 后期绑定(bind)方法重载不起作用

delphi - 如何访问后期绑定(bind)的嵌套属性和方法?

Java:后期绑定(bind)以及在哪里使用它?有什么好处?

c# - 使用自定义 FluentValidator 验证器验证枚举

c# - VS2010 加载项,向上下文菜单添加命令?

c# - 从 MVC 中的表单发布列表 <Model>

vba - 获取 PowerPoint 形状的 .OLEFormat.Object 属性时出错(来自 Excel-VBA 的 LateBinding)

c# - 在 C# 中使用后期绑定(bind)获取特定的 Excel 实例