【发布时间】:2019-06-05 12:26:27
【问题描述】:
我希望foreach 循环中的var 隐式转换我的自定义IEnumerable 的项目。它在内部Dictionary 上循环,主要是一个包装器。我尝试了通用和非通用IEnumerable。
我想了解在 foreach 循环中支持隐式转换需要什么。
public class Bewerbung : IEnumerable<KeyValuePair<string, string>>
{
protected Dictionary<string, string> internDic = new Dictionary<string, string>();
public IEnumerator GetEnumerator()
{
return internDic.GetEnumerator();
}
IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
{
return internDic.GetEnumerator() ;
}
}
var bewerbung = new Bewerbung();
foreach (var testi in bewerbung)
{
}
testi 始终是一个对象,而不是 KeyValuePair,就像它应该的那样。
我知道我可以将显式转换用于实际用途,但我想了解我的方法有什么问题。其他IEnumerables 可以隐式转换,为什么这不适用于我的自定义类?
【问题讨论】:
标签: c# casting ienumerable