从字符串中获取对象名称(C#/ XNA)

时间:2014-01-05 05:03:19

标签: c# string xna integer converter

我想在我的游戏中编写一种命令行调试功能,允许用户输入变量的名称:

int number = 38;

...只需输入“number”或该变量的名称,即可访问该变量的值。 有没有办法将字符串转换为变量名,或者从这样的等效字符串中获取变量的值?

return GetVariable("number");

或者这是完全错误的方法吗?有没有其他方法可以随时获取任何变量的值,只需在某个地方输入?

以下是人们应该使用的内容:

public static T getFromString<T>(object context, string get)
    {
        var use = context;
        BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
        FieldInfo field = use.GetType().GetField(get, bindFlags);
        Object value = field.GetValue(use);
        return (T)value;
    }

此代码有效。您只需要确保您的变量在类中定义,如下面的Foo。耶!

编辑:我再次编辑了该方法,现在它返回带有类型的变量,并使用您自己的上下文。像这样使用它:

getFromString<int>(Game1, "number");

1 个答案:

答案 0 :(得分:1)

如前所述,您需要使用反射或字典查找。对于反射,它会像(假设私有实例字段):

FieldInfo field = type.GetField(fieldName, bindFlags);
Object value field.GetValue(instance);

GetValue返回一个Object。如果要返回控制台,可能需要调用Console.WriteLine(value.ToString())。

<强>更新

根据您的评论更新。我建议您参考评论中已经提供的反思链接。我总是觉得从一个有效的例子开始是最简单的,所以我在下面提供了一个。这应该达到你想要的。您可能需要调整它以满足您的特定要求或应用程序。

class Program
{
    public class Foo
    {
        int number = 38;
    }

    static void Main( string[] args )
    {
        Foo foo = new Foo(); //create a new instance of the type that contains variable that you want the value of
        BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; //define binding flags
        FieldInfo field = foo.GetType().GetField( "number", bindFlags ); //get the field from the object that has this name
        Object value = field.GetValue( foo ); //get the value of the field.
        Console.WriteLine( value.ToString() ); //output the value to the console.
    }
}