c#中反射中的SetValue [英] SetValue in reflection in c#

查看:60
本文介绍了c#中反射中的SetValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码:

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

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

In the code above we should pass two arguments for SetValue. First,The object that we want to set its property. Second,the new value. But we select the specific property.

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

Why we should pass the first parameter to set the value as we have set the future object before!?

推荐答案

因为 future 对象是一个实例.PropertyInfo 是从类型 (Type type = future.GetType();) 中检索的,并且没有绑定到任何实例.这就是您必须在 SetValue() 中传递实例的原因.

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. That's why you have to pass the instance in the SetValue().

所以:

var future = new Future();

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

propertyInfo.SetValue(future, value);

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

You can reuse the propertyInfo to set properties of other instances.

这篇关于c#中反射中的SetValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆