C#使用字符串作为类字段名称 [英] C# use string as a class field name

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

问题描述

很抱歉,如果该图块具有误导性.我想做的是使用字符串从类中获取值.我有什么:

Sorry if the tile is misleading. What i would like to do is to use a string to get the values from a class. What i have:

class foo
{
    public string field1 {get;set;}
    public string field2 {get;set;}
}

public void run()
{
    //Get all fields in class
    List<string> AllRecordFields = new List<string>();
    Type t = typeof(foo);
    foreach (MemberInfo m in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    {
        AllRecordFields.Add(m.Name);
    }

    foo f = new foo();
    foreach(var field in AllRecordFields)
    { 
        //field is a string with the name of the real field in class
        f.field = "foobar";
    }
}

这是一个非常简单的示例,所以问题出在 f.field ="foobar"; field 是一个字符串,其名称为我想为其分配值的真实类字段.

This a really simple example, so the problem is on the line f.field = "foobar"; The field is a string with a name of the real class field what i want to assignt the value to.

推荐答案

使用 PropertyInfo 代替 MemberInfo ,然后使用 SetValue .

public void run()
{
  foo f = new foo();
  Type t = typeof(foo);

  foreach (PropertyInfo info in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  {
     info.SetValue(f, "foobar", new object[0]);
  }
}

这篇关于C#使用字符串作为类字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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