通过传递名称获取并设置字段值 [英] Get and set the field value by passing name

查看:37
本文介绍了通过传递名称获取并设置字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中有一个字段,其名称如下:

I have a field in a class with a random name like:

class Foo {
    public string a2de = "e2"
}

我在另一个变量中有此字段的名称,例如:

I have the name of this field in another variable like:

string vari = "a2de"

我是否可以使用 vari a2de 的值>?

Can I get or set the value of field a2de by using the value of vari?

like:

getvar(vari)

setvar(vari) = "e3"


推荐答案

获取 targetObject 上属性的值:

var value = targetObject.GetType().GetProperty(vari).GetValue(targetObject, null);

要获取字段的值,它类似于:

To get the value of a field it's similar:

var value = targetObject.GetType().GetField(vari).GetValue(targetObject, null);

如果属性/字段不是公共的或它是从基类继承的,则需要为 GetProperty GetField 提供明确的 BindingFlags

If the property/field is not public or it has been inherited from a base class, you will need to provide explicit BindingFlags to GetProperty or GetField.

这篇关于通过传递名称获取并设置字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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