【问题标题】:Compiler Error MC3030: Owner Class of IEnumerable Property must Implement IAddChild编译器错误 MC3030:IEnumerable 属性的所有者类必须实现 IAddChild
【发布时间】:2015-05-22 21:35:44
【问题描述】:

我正在尝试在 .NET 4.0 客户端配置文件中构建自定义 Panel 子类。我是这样开始的:

public class MyPanel : Panel
{
    public MyPanel()
    {
    }
}

这可以很好地与 XAML 中的一些子控件集成(localMyPanel 所在的命名空间的前缀):

<local:MyPanel>
    <Button/>
    <CheckBox/>
</local:MyPanel>

现在,我想向MyPanel 添加一个集合属性。因此,我扩展了这个类:

public class MyPanel : Panel
{
    public MyPanel()
    {
    }

    private readonly List<Button> someList = new List<Button>();

    public IList<Button> SomeList {
        get {
            return someList;
        }
    }
}

到目前为止,一切顺利,上面的 XAML 代码仍然可以编译。

但是,我想在 XAML 中向 SomeList 属性添加一些元素,所以我写:

<local:MyPanel>
    <local:MyPanel.SomeList>
        <Button/>
    </local:MyPanel.SomeList>
    <Button/>
    <CheckBox/>
</local:MyPanel>

不幸的是,这不再编译,因为编译器输出以下错误:

Bei der Eigenschaft "SomeList" handelt es sich um eine schreibgeschützte IEnumerable-Eigenschaft。 Das bedeutet, dass "IAddChild" von "MyNamespace.MyPanel" implementiert werden muss。 Zeile 9 位置 4. (MC3030)

英文(根据Unlocalize):

MC3030:“SomeList”属性是只读的 IEnumerable 属性,这意味着“MyNamespace.MyPanel”必须实现 IAddChild。

显然,这是指System.Windows.Markup.IAddChild interface。没问题,似乎不太复杂 - 所以,我在MyPanel 中实现了IAddChild(首先以一种没有任何用处的方式开始,但这不重要,因为这些方法不会被执行在应用程序编译之前):

public class MyPanel : Panel, IAddChild
{
    public MyPanel()
    {
    }

    private readonly List<Button> someList = new List<Button>();

    public IList<Button> SomeList {
        get {
            return someList;
        }
    }

    public void AddChild(object value)
    {
        throw new NotImplementedException();
    }

    public void AddText(string text)
    {
        throw new NotImplementedException();
    }
}

这应该可以,但是...... 不,它没有!我在编译时仍然遇到同样的错误 MC3030。

我完全按照错误信息的指示做了,但是错误并没有消失。我是否遗漏了编译器对我保密的任何其他修改?

documentation on IAddChild 似乎没有提及与这种情况相关的任何内容。此外,谷歌搜索连接到IAddChildWPFMC3030 只会显示aforementioned Unlocalize entry 作为唯一相关结果。显然,错误 MC3030 是一个非常难以理解的错误,迄今为止很少有开发人员遇到过。

【问题讨论】:

    标签: .net wpf xaml .net-4.0 compiler-errors


    【解决方案1】:

    出现该问题是因为该属性公开为通用集合类型。如果您将属性类型从 IList&lt;Button&gt; 更改为 IList,错误应该会消失。如果该属性表示最终将在设计器中产生某些可见效果的集合,您可能还需要考虑将设计器序列化可见性设置为内容。

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public IList SomeList
    {
        get
        {
            return someList;
        }
    }
    

    【讨论】:

    • 是的。这并不理想,但我认为使用来自 xaml 的泛型集合的唯一方法是创建自己的标记扩展(例如在 this blog post 中讨论的内容)。但是,由于该属性是由通用集合支持的,因此如果您尝试将错误的内容放入其中,则会出现异常。
    • 那为什么它适用于内置类型,例如 ColumnDefinitions propertyGrid
    • 我不确定你的意思。据我所知,XAML 中使用的内置类型都不是泛型集合。他们总是专业的。您提到的属性是ColumnDefinitionCollection 而不是List&lt;ColumnDefinition&gt;
    • 好吧,ColumnDefinitionCollection 确实实现了 IList&lt;T&gt;(尽管它也实现了 IList)。
    猜你喜欢
    • 2021-09-09
    • 2017-01-15
    • 2021-06-20
    • 2016-01-18
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多