使用字符串中的名称获取变量的值 [英] Get value of a variable using its name in a string

查看:227
本文介绍了使用字符串中的名称获取变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从变量名中获取变量的值。

I want to get the value of a variable from its name.

为了澄清起见,XML文档将变量名作为字符串传递;我想获取值。

To clarify, an XML document delivers the variable name as a string; I want to get the value.

像这样的事情:

string bublegumA = "strawberry";
string bubblegumB = "banana";   

//get which variable from the XML

string fromXML = "bubblegumB";

string output = getValue(fromXML);

//it should return "banana"


推荐答案

基本上,这是反射的应用程序:

Basically, this is an application of reflection:

如果它是字段,这应该可以工作:

This should work, if it's a field:

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

因此,如果您的班级是:

So if your class is:

public class MyClass
{
    public string BubblegumA = "Strawberry";
}

然后在您的主班:

public static void Main()
{
    MyClass targetObject = new MyClass();

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

    //value should = Strawberry
}

这篇关于使用字符串中的名称获取变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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