考虑以下代码:
var future = new Future();
future.GetType().GetProperty(info.Name).SetValue(future, converted);
在上面的代码中,我们应该为SetValue
传递两个参数。首先,我们要设置其属性的对象。第二,新的价值。但我们选择了具体的财产。
为什么我们应该传递第一个参数来设置值,因为我们之前设置了未来的对象!?
答案 0 :(得分:17)
因为 future 对象是一个实例。 PropertyInfo 是从类型(Type type = future.GetType();
)中检索的,并未绑定到任何实例。这就是你必须在 SetValue()中传递实例的原因。
所以:
var future = new Future();
var propertyName = "...";
Type type = future.GetType();
PropertyInfo propertyInfo = type.GetProperty(propertyName);
propertyInfo.SetValue(future, value);
您可以重复使用 propertyInfo 来设置其他实例的属性。
答案 1 :(得分:4)
下面
future.GetType()
future
仅用于获取其类型。实际上它与
Type t = future.GetType();
t.GetProperty(info.Name).SetValue(future, converted);
在上面代码的第二行,关于用什么对象获取类型的所有知识都丢失了,我们正在处理类型本身。稍后,当我们获得有关该类型属性的信息时,我们需要知道它应该与哪个对象一起使用,因此我们再次提供future
。
答案 2 :(得分:3)
您之前没有设置未来对象 - 您只是提取其类型,然后对其进行操作。您最终得到的是PropertyInfo
对象,它在Future
类型的任何实例上引用该属性。
答案 3 :(得分:0)
您可以轻松执行以下操作:
typeof(Future).GetProperty(info.Name).SetValue(future, converted);
如何在没有future
参数的情况下进行实例?
答案 4 :(得分:0)
考虑这两个类:
class Future
{
public int MyProperty { get; set; }
}
class FarFuture : Future { }
看看这段代码:
var future = new Future();
var farFuture = new FarFuture();
future.GetType().GetProperty(info.Name).SetValue(farFuture, converted);
PropertyInfo
未绑定到实例,而是绑定到类型。