使用包含变量名称的字符串访问变量 [英] Accessing a variable using a string containing the variable's name

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

问题描述

我正在从数据库中读取字符串变量的名称(例如 _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);
        }
    }
}

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

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