简体   繁体   English

SetValue在c#中的反射

[英]SetValue in reflection in c#

Consider this code: 考虑以下代码:

var future = new Future();
future.GetType().GetProperty(info.Name).SetValue(future, converted);

In the code above we should pass two arguments for SetValue . 在上面的代码中,我们应该为SetValue传递两个参数。 First,The object that we want to set its property. 首先,我们要设置其属性的对象。 Second,the new value. 第二,新的价值。 But we select the specific property. 但我们选择了具体的财产。

Why we should pass the first parameter to set the value as we have set the future object before!? 为什么我们应该传递第一个参数来设置值,因为我们之前设置了未来的对象!?

Because the future object is an instance. 因为将来的对象是一个实例。 The PropertyInfo is retrieved from the type ( Type type = future.GetType(); ) and isn't bound to any instance. PropertyInfo是从类型( Type type = future.GetType(); )中检索的,并未绑定到任何实例。 That's why you have to pass the instance in the SetValue() . 这就是你必须在SetValue()中传递实例的原因。

So: 所以:

var future = new Future();

var propertyName = "...";
Type type = future.GetType();
PropertyInfo propertyInfo = type.GetProperty(propertyName);

propertyInfo.SetValue(future, value);

You can reuse the propertyInfo to set properties of other instances. 您可以重用propertyInfo来设置其他实例的属性。

Here 这里

future.GetType()

future was used only to obtain its type. future仅用于获取其类型。 Effectively it is the same as 实际上它是一样的

Type t = future.GetType();
t.GetProperty(info.Name).SetValue(future, converted);

On the second line of the code above all the knowledge about what object was used to get the type is lost, and we are dealing with the type itself. 在上面代码的第二行,关于用什么对象来获取类型的所有知识都丢失了,我们正在处理类型本身。 Later, when we have information about the property of the type, we need to know what object it should be used with, so we are providing future yet again. 之后,当我们获得有关该类型属性的信息时,我们需要知道它应该与哪个对象一起使用,因此我们将再次提供future

You haven't set the future object before - you've simply extracted its type, and then operated on that. 您之前没有设置未来对象 - 您只是提取其类型,然后对其进行操作。 What you end up with is a PropertyInfo object that refers to that property on any instance of type Future . 您最终得到的是一个PropertyInfo对象,它引用任何类型为Future实例上的该属性。

You could easily do following: 你可以轻松做到以下几点:

typeof(Future).GetProperty(info.Name).SetValue(future, converted);

How could the instance be taken without future parameter? 如何在没有future参数的情况下进行实例?

Consider these 2 classes: 考虑这两个类:

class Future
{
    public int MyProperty { get; set; }
}
class FarFuture : Future { }

Take a look at this code: 看看这段代码:

var future = new Future();
var farFuture = new FarFuture();
future.GetType().GetProperty(info.Name).SetValue(farFuture, converted);

The PropertyInfo is not bound to an instance, but to a type. PropertyInfo不是绑定到实例,而是绑定到类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM