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/