繁体   English   中英

如何在课堂上实现Foreach,以便获得每个键的名称和值?

[英]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; }
}

我想将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"
}

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

您无法枚举类的属性 (以简单的方式)

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

注意:确实可以使用Reflection枚举类的属性,但这不是您要解决的方法。

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>

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

谢谢eveyrone! 看来我需要使用反射来达成目标。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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