简体   繁体   中英

How to implement Foreach in my class so I can get each key name and value?

public class Zone
{
    public string zoneID { get; set; }
    public string zoneName { get; set; }
    public string zonePID { get; set; }
}

I want to use foreach for Zone, like

var zone = new Zone(){zoneId = "001", zoneName = "test"};
foreach(var field in zone)
{
   string filedName = field.Key;  //for example : "zoneId"
   string filedValue = filed.value; //for example : "001"
}

I just don't konw how to implement GetEnumerator() in Zone class

You can't enumerate the properties of a class (in a simple way)

Use a string array or string list or a dictionary inside your class.

Note: Indeed it is possible to enumerate the properties of a class using Reflection, but this is not the way to go in your case.

foreach(var field in zone)
{
   string filedName = field.zoneID;  //Id of property from Zone Class
   string filedValue = filed.zoneName ; //name of property from Zone Class
}

You could equip Zone with this method:

public Dictionary<string, string> AsDictionary()
{
  return new Dictionary<string, string>
    {
      { "zoneID", zoneID },
      { "zoneName", zoneName },
      { "zonePid", zonePid },
    };
 }

Then you can foreach that.

Alternatively, you can implement GetEnumerator() as an iterator block where you yield return the three new KeyValuePair<string, string> .

I am not saying that this design is particularly recommendable.

Thanks eveyrone! It Seems I need to use reflection to achieve the goal.

System.Reflection.PropertyInfo[] pis = zone.GetType().GetProperties();
foreach (var prop in pis)
{
    if (prop.PropertyType.Equals(typeof(string))) 
    {
        string key = prop.Name;
        string value = (string)prop.GetValue(zome, null);
        dict.Add(key, value); //the type of dict is Dictionary<str,str>
    }
}

Just don't know wheather this is a good solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM