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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11122241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:35:07  来源:igfitidea点击:

Accessing a variable using a string containing the variable's name

c#stringvariablesreflection

提问by Rick Price

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.

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

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?

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

回答by Olivier Jacot-Descombes

Usually you would create a class representing the values of one table record. If your table has an IDa FirstNameand a LastNamecolumn, you would create a class like this

通常您会创建一个类来表示一个表记录的值。如果你的表有一个IDaFirstName和一个LastName列,你会创建一个这样的类

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Then you create a list of persons

然后你创建一个人员列表

var people = new List<Person>();

Now you can add persons to the list.

现在您可以将人员添加到列表中。

var p = new Person();
p.ID = 5;
p.FirstName = "John";
p.LastName = "Doe";
people.Add(p);


You can use a DataReader in order to read from a table

您可以使用 DataReader 来读取表

string sql = "SELECT * FROM tblPerson WHERE LastName LIKE @pattern";
cmd = new SqlCommand(sql);
cmd.Connection = "server=test;uid=sa;pwd=manager;database=northwind";
cmd.Parameters.AddWithValue("@pattern", "A%"); // Names beginning with "A"
using (SqlDataReader reader = cmd.ExecuteReader()) {
    // Get column indexes
    int idOrdinal = reader.GetOrdinal("ID");
    int firstNameOrdinal = reader.GetOrdinal("FirstName");
    int lastNameOrdinal = reader.GetOrdinal("LastName");

    while(reader.Read()) {
        var p = new Person();
        p.ID = reader.GetInt32(idOrdinal);
        p.FirstName = reader.GetString(firstNameOrdinal);
        p.LastName = reader.GetString(lastNameOrdinal);
        people.Add(p);
    }
}

回答by Kevin Aenmey

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
    }
}

EDIT:@Rick, to respond to your comment:

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

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);
        }
    }
}

回答by andrews_nz

If you want to get the value of a field based on its string name you will have to use reflection.

如果您想根据字符串名称获取字段的值,则必须使用反射。

class MyClass
{
    public int DataFile { get; set; }

    public int _datafile;
}

var ob = new MyClass();
var typ = typeof(MyClass);
var f = typ.GetField("_datafile");
var prop = typ.GetProperty("DataFile");
var val = f.GetValue(ob);
var propVal = prop.GetValue(ob);