![](/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.