Skip to main content
 首页 » 编程设计

c#之如何在我的类中实现 Foreach 以便我可以获得每个键名和值

2024年02月06日10傻小

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

我想为 Zone 使用 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()

请您参考如下方法:

你不能枚举一个类的属性(以一种简单的方式)

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

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