如何在我的类中实现 Foreach,以便我可以获取每个键名称和值

本文关键字:获取 我可以 我的 Foreach 实现 | 更新日期: 2025-02-19 13:14:56

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

我想将foreach用于区域,例如

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

我只是不知道如何在区域类中实现GetEnumerator()

如何在我的类中实现 Foreach,以便我可以获取每个键名称和值

不能枚举类的属性(以简单的方式(

在类中使用字符串数组、字符串列表或字典。

注意:实际上可以使用反射枚举类的属性,但这不是您的情况。

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
}
你可以

用这种方法装备Zone

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

然后你可以foreach

或者,您可以将GetEnumerator()实现为迭代器块,您可以在其中yield return三个new KeyValuePair<string, string>

我并不是说这种设计特别值得推荐。

谢谢伊芙龙!看来我需要用反思来实现目标。

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

只是不知道这是一个很好的解决方案。

相关文章: