【发布时间】: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 创建构造函数并像那样传递参数/填充。我想一一填充它的属性。
请链接其他有用的实例填充方法。我知道这是最愚蠢的。
【问题讨论】:
-
你到底想做什么?你为什么不做简单的事情并使用prop.SetValue(testclassInstance, "your string")?
-
您的参数数组太大:
string[] parameters = new string[1];将解决它。 -
您使用的搜索引擎似乎无法找到好的内容。尝试 Bing - bing.com/search?q=c%23+set+property+reflection 或 Google - google.com/?q=c%23+set+property+reflection - 都将链接副本作为最佳建议。
标签: c# late-binding