使用包含变量名称的字符串访问变量

使用包含变量名称的字符串访问变量

问题描述:

我正在从数据库中读取字符串变量的名称(例如 _datafile)。我想知道如何使用此字符串访问程序中的命名变量。

I am reading the name of a string variable from the database (e.g. "_datafile"). I want to know how I can access a named variable within my program using this string.

我已经尝试过使用字典,哈希表和switch-case语句但我想让变量动态地自行解决。

I have already tried using a dictionary, hash table, and a switch-case statement but I would like to have the variable resolve itself dynamically. Is this possible?

您是否要使用字段名作为字符串来获取字段的值? / p>

Do you mean you want to get the value of a field using the field name as a string?

public class MyClass
{
    public string _datafile;

    public MyClass()
    {
        _datafile = "Hello";
    }

    public void PrintField()
    {
        var result = this.GetType().GetField("_datafile").GetValue(this); 
        Console.WriteLine(result); // will print Hello
    }
}

编辑: @Rick,以回应您的评论:

@Rick, to respond to your comment:

public class MyClass
{
    public IEnumerable<string> _parameters = new[] { "Val1", "Val2", "Val3" };

    public void PrintField()
    {
        var parameters = this.GetType().GetField("_parameters").GetValue(this) as IEnumerable;

        // Prints:
        // Val1
        // Val2
        // Val3
        foreach(var item in parameters)
        {
            Console.WriteLine(item);
        }
    }
}