SetValue在c#中的reflection
考虑以下代码:
var future = new Future(); future.GetType().GetProperty(info.Name).SetValue(future, converted);
在上面的代码中,我们应该为SetValue
传递两个参数。 首先,我们要设置其属性的对象。 第二,新的价值。 但我们选择了具体的财产。
为什么我们应该传递第一个参数来设置值,因为我们之前设置了未来的对象!?
因为将来的对象是一个实例。 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来设置其他实例的属性。
这里
future.GetType()
future
仅用于获取其类型。 实际上它是一样的
Type t = future.GetType(); t.GetProperty(info.Name).SetValue(future, converted);
在代码的第二行上面,所有关于用什么对象来获取类型的知识都丢失了,我们正在处理类型本身。 之后,当我们获得有关该类型属性的信息时,我们需要知道它应该与哪个对象一起使用,因此我们将再次提供future
。
您之前没有设置未来对象 – 您只需提取其类型,然后对其进行操作。 您最终得到的是一个PropertyInfo
对象,它引用任何类型为Future
实例上的该属性。
你可以很容易地做到以下:
typeof(Future).GetProperty(info.Name).SetValue(future, converted);
如果没有future
参数,如何进行实例?
考虑这两个类:
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
未绑定到实例,而是绑定到类型。