C# use string as a class field name

2019-08-08 05:22发布

问题:

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

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.

回答1:

Use PropertyInfo instead of MemberInfo and then 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]);
  }
}


回答2:

First of all, it is better to use Properties instead of fields. Second your fields are private, can't be accessed from outside foo. You need to declare them as public.



回答3:

For your example you have to use reflection to access those files. But that is slow and it is not very good style. You better use the class directly (with property setter) or us an interface.



回答4:

Add method into foo class to change all properties

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

        public void SetValueForAllString( string value)
        {
            var vProperties = this.GetType().GetProperties();
            foreach (var vPropertie in vProperties)
            {
                if (vPropertie.CanWrite 
                    && vPropertie.PropertyType.IsPublic 
                    && vPropertie.PropertyType == typeof(String))
                {
                    vPropertie.SetValue(this, value, null);
                }
            }

        }
    }

    foo f = new foo() { field1 = "field1", field2 = "field2" };
                f.SetValueForAllString("foobar");
                var field1Value = f.field1; //"foobar"

             var field2Value = f.field2; //"foobar"


标签: c# field