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

时间:2015-03-30 06:34:48

标签: c# foreach

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

我想将foreach用于Zone,比如

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()

4 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:0)

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
}

答案 2 :(得分:0)

您可以使用此方法装备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>

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

答案 3 :(得分:0)

谢谢大家!似乎我需要使用反射来实现目标。

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

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