![](/img/trans.png)
[英]Does Task objects internally contain a collection of ContinueWith tasks?
[英]Why does this collection seem to contain objects?
我有一個類“ImageElementCollection:ConfigurationElementCollection”包含類“ImageElement:ConfigurationElement”的元素。
在StackOverflow上使用其他一些非常聰明的人的建議,我已經想出如何在我的程序中使用這些項目:
MonitorConfig Config = (MonitorConfig)ConfigurationManager.GetSection("MonitorConfig");
但是,當我嘗試訪問此集合中的項目時...
foreach (var image in Config.Images) Debug.WriteLine(image.Name);
...我最終在Name屬性下使用了波浪線,因為盡管我付出了最大的努力,“image”已被聲明為對象而不是ImageElement。
這是我在我的聲明中做錯了什么,或者這只是每個人只需通過在那個foreach中交換“var”for“ImageElement”來處理的事情?
配置處理程序的代碼如下:
public class MonitorConfig : ConfigurationSection
{
[ConfigurationProperty("Frequency", DefaultValue = 5D, IsRequired = false)]
public double Frequency
{
get { return (double)this["Frequency"]; }
}
[ConfigurationProperty("Images", IsRequired = false)]
public ImageElementCollection Images
{
get { return (ImageElementCollection)this["Images"]; }
}
}
[ConfigurationCollection(typeof(ImageElement), AddItemName = "Image")]
public class ImageElementCollection : ConfigurationElementCollection
{
public ImageElement this[object elementKey]
{
get { return (ImageElement)BaseGet(elementKey); }
}
public void Add(ImageElement element)
{
base.BaseAdd(element);
}
protected override ConfigurationElement CreateNewElement()
{
return new ImageElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ImageElement)element).Name;
}
}
public class ImageElement : ConfigurationElement
{
[ConfigurationProperty("Name", IsRequired = true, IsKey = true)]
public string Name
{
get { return (string)this["Name"]; }
}
}
Andrew Kennan在上面的評論中提供了答案:這個集合似乎只包含對象,因為它沒有實現IEnumerable <T>。
此外,可以通過稍微調整配置處理程序來解決該問題。 只需添加IEnumerable接口,如下所示......
public class ImageElementCollection : ConfigurationElementCollection, IEnumerable<ImageElement>
...然后在類的主體中粘貼一個類似這樣的方法:
public new IEnumerator<ImageElement> GetEnumerator()
{
var iter = base.GetEnumerator();
while (iter.MoveNext()) yield return (ImageElement)iter.Current;
}
謝謝你,安德魯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.