【发布时间】:2013-02-20 16:27:32
【问题描述】:
我有一个“ImageElementCollection:ConfigurationElementCollection”类,其中包含“ImageElement:ConfigurationElement”类的元素。
根据 StackOverflow 上其他一些非常聪明的人的建议,我已经弄清楚了如何在我的程序中使用这些项目:
MonitorConfig Config = (MonitorConfig)ConfigurationManager.GetSection("MonitorConfig");
但是,当我尝试访问此集合中的项目时...
foreach (var image in Config.Images) Debug.WriteLine(image.Name);
...我在 Name 属性下得到了波浪线,因为尽管我尽了最大努力,但“图像”已被声明为对象而不是 ImageElement。
这是我在声明中做错了什么,还是每个人都只是通过在上面的那个 foreach 中将“var”交换为“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"]; }
}
}
【问题讨论】:
-
尝试将
var image换成ImageElement image。它可能是模棱两可的,只是将其视为类型对象。 (编辑:在你的 foreach 中,如果我不清楚的话......) edit2:我看到你已经这样做了,并且似乎暗示它有效。然后我想我的意思是说“是的,这就是我解决它的方式。” -
是的,效果很好。我觉得奇怪的是,当用“var. "认为这可能意味着我的处理程序坏了?
-
ConfigurationElementCollection 实现了 ICollection 和 IEnumerable,它们不会向编译器提供关于它包含的元素类型的提示,因此它默认为 Object 类型的元素。如果集合实现了通用接口 IEnumerable
,编译器将能够确定它应该使用 T 代替 var。 -
我可以自己实现 IEnumerable
吗? (好吧,是的,我只是去试试看,但仍然......)
标签: c# xml configuration app-config