为什么BindingList <t>不必完全实现其接口?</t>

时间:2014-02-05 09:36:30

标签: c# .net oop interface

BindingList<T>实施IBindingListIBindingList上的方法之一是

void ApplySort(PropertyDescriptor property, ListSortDirection direction);

但是BindingList<T>没有实现此方法。相反,它实现了

protected virtual void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction);

显然ApplySortCore有一个不同的名称而且不公开,所以我看不出它如何满足IBindingList界面的要求,但这与IBindingList最接近实际上是要求。

那么这个类怎么可能没有完全实现它的接口呢?

3 个答案:

答案 0 :(得分:3)

我猜BindingList使用显式接口实现来隐藏接口成员。

试试这个

interface IX
{
    public string Var {get;}
}

public class X : IX
{
    string IX.Var { get { return "x"; } }
}

public class Y
{
    public Y()
    {
        X x = new X();
        string s = x.Var; // Var is not visible and gives a compilation error.

        string s2 = ((IX)x).Var; // this works. Var is not hidden when using interface directly.
    }
}

答案 1 :(得分:1)

BindingList明确地实现了这里的接口是msdn link http://msdn.microsoft.com/en-us/library/ms132686%28v=vs.85%29.aspx,这就是为什么你没有在类上看到它。

为了能够调用您需要首先将对象强制转换为IBindingList的方法。

答案 2 :(得分:1)

的BindingList&LT; T&GT; 实际上实现了ApplySort,但它是一个显式的接口实现。这意味着如果你有一个BindingList&lt; T&gt;类型的变量。你不会在其上看到ApplySort方法,但是如果你该变量强制转换为IBindingList,那么你将看到ApplySort方法。显式接口实现仅在您将对象视为该接口时才可见。

如果查看MSDN documentation并向下滚动到“显式接口实现”标题,您将看到其中列出的ApplySort(以及许多其他方法)。