SetValue在c#中的反射

Poo*_*ani 9 c# reflection

考虑以下代码:

var future = new Future();
future.GetType().GetProperty(info.Name).SetValue(future, converted);
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我们应该传递两个参数SetValue.首先,我们要设置其属性的对象.第二,新的价值.但我们选择了具体的财产.

为什么我们应该传递第一个参数来设置值,因为我们之前设置了未来的对象!?

Jer*_*gen 17

因为将来的对象是一个实例.所述的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);
Run Code Online (Sandbox Code Playgroud)

您可以重用propertyInfo来设置其他实例的属性.