[英]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 我想将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"
}
I just don't konw how to implement GetEnumerator()
in Zone class 我只是不知道如何在Zone类中实现GetEnumerator()
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. 注意:确实可以使用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
}
You could equip Zone
with this method: 您可以使用以下方法为Zone
配备:
public Dictionary<string, string> AsDictionary()
{
return new Dictionary<string, string>
{
{ "zoneID", zoneID },
{ "zoneName", zoneName },
{ "zonePid", zonePid },
};
}
Then you can foreach
that. 然后你就可以foreach
说。
Alternatively, you can implement GetEnumerator()
as an iterator block where you yield return
the three new KeyValuePair<string, string>
. 或者,您可以将GetEnumerator()
实现为迭代器块,并在其中yield return
三个new KeyValuePair<string, string>
。
I am not saying that this design is particularly recommendable. 我并不是说这种设计特别值得推荐。
Thanks eveyrone! 谢谢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. 只是不知道惠特尔,这是一个很好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.