【问题标题】:Why does this collection seem to contain objects?为什么这个集合似乎包含对象?
【发布时间】: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


【解决方案1】:

Andrew Kennan 在上面的 cmets 中提供了答案:这个集合似乎只包含对象,因为它没有实现 IEnumerable

此外,可以通过稍微调整配置处理程序来解决该问题。只需添加IEnumerable接口如下...

public class ImageElementCollection : ConfigurationElementCollection, IEnumerable<ImageElement>

...然后在类的主体中粘贴一个有点像这样的方法:

public new IEnumerator<ImageElement> GetEnumerator()
{
    var iter = base.GetEnumerator();
    while (iter.MoveNext()) yield return (ImageElement)iter.Current;
}

谢谢你,安德鲁。

【讨论】:

  • (顺便说一句,如果你愿意,喜欢......回答,我会选择你的。:P)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-28
  • 2019-04-05
  • 2017-03-10
  • 1970-01-01
  • 2017-12-30
  • 2012-09-24
  • 1970-01-01
相关资源
最近更新 更多