且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用字符串中的名称获取变量的值

更新时间:2023-02-18 21:00:05

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

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
}