BindingList<T>中的T是实现其他接口的接口。

4

我卡在了BindingList上,其中T是扩展A接口的接口。当我在绑定中使用这个bindingList时,只有T的属性可见,而从继承的A接口继承的属性则不可见。为什么会发生这种情况?看起来像是一个.NET的bug。这对我的两个项目来说是必要的,以共享一些公共功能。同时,当PropertyChanged事件从基本实现中传递时,绑定列表的PropertyDescriptor为空。附加接口和实现。最后是SetUp方法。

interface IExtendedInterface : IBaseInterface
{
    string C { get; }
}

interface IBaseInterface : INotifyPropertyChanged
{
    string A { get; }
    string B { get; }
}

public class BaseImplementation : IBaseInterface
{
    public string A
    {
        get { return "Base a"; }
    }

    public string B
    {
        get { return "base b"; }
        protected set
        {
            B = value;
            OnPropertyChanged("B");
        }
    }

    protected void OnPropertyChanged(string p)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(p));
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}

public class ExtendedImplementation : BaseImplementation, IExtendedInterface
{
    public string C
    {
        get { return "Extended C"; }
    }
}

 private void SetupData()
    {
        BindingList<IExtendedInterface> list = new BindingList<IExtendedInterface>();
        list.Add(new ExtendedImplementation());
        list.Add(new ExtendedImplementation());
        dataGridView1.DataSource = list;
    }

1
请勿在文件中附加代码。我们不需要整个项目。请将您的示例程序拆分为最小可能的程序,并将其作为文本/代码粘贴。 - Josh Smeaton
“不可见”是什么意思?如果您绑定到这些属性,它们可能会显示为不可访问,但这只是设计时绑定的结果,当您运行应用程序时,一切都应该正常。 - Piotr Auguscik
当绑定列表触发ItemChanged事件时,如果涉及到BaseInterface的属性,则它们在绑定网格中不可见,然后我会得到null PropertyDescriptor。但是在应用程序运行时它不起作用。只需粘贴代码并查看即可,由于我的声望,我无法发布图像。 - user1079952
1个回答

6
属性是通过(间接地)使用TypeDescriptor.GetProperties(typeof(T))获得的,但其行为符合预期。除非它们出现在类型的公共API上(对于接口而言,这意味着出现在立即类型上),否则从接口继承的属性永远不会被返回,即使是基于类的模型。类继承不同,因为那些成员仍然在公共API上。当一个接口:ISomeOtherInterface时,那是“实现”,而不是“继承”。为了举例说明可能存在的问题,请考虑以下情况(完全合法):
interface IA { int Foo {get;} }
interface IB { string Foo {get;} }
interface IC : IA, IB {}

现在,IC.Foo是什么?您也许可以通过为接口注册自定义TypeDescriptionProvider或使用ITypedList来绕过此问题,但这两者都很棘手。老实说,数据绑定对类的支持比接口更加简单易用。

感谢您的解释。这将有助于未来避免与接口绑定相关的问题。 - user1079952

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接