【问题标题】:Why doesn't BindingList<T> have to fully implement its interfaces?为什么 BindingList<T> 不必完全实现它的接口?
【发布时间】:2014-03-01 15:46:54
【问题描述】:

BindingList&lt;T&gt; 实现IBindingListIBindingList 上的方法之一是

void ApplySort(PropertyDescriptor property, ListSortDirection direction);

但是BindingList&lt;T&gt; 没有实现这个方法。相反,它实现了

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

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

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

【问题讨论】:

  • 您从哪里获得此信息? msdn doc 将其列在显式接口实现下。
  • @LorentzVedeler 我现在看到了。我刚刚在视觉工作室打 F12。但是我去了文档,现在我看到它已经明确实现了。您只是无法从击中 F12 中看出这一点。谢谢。

标签: c# .net oop interface


【解决方案1】:

BindingList确实实际上实现了ApplySort,但它是作为显式接口实现的。这意味着如果您有一个 BindingList 类型的变量,您将不会在其上看到 ApplySort 方法,但如果您将该变量 cast 到 IBindingList 您将看到 ApplySort 方法.显式接口实现仅在您将对象视为该接口时可见。

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

【讨论】:

    【解决方案2】:

    这里的BindingList明确实现接口是msdn链接http://msdn.microsoft.com/en-us/library/ms132686%28v=vs.85%29.aspx,所以在类上看不到。

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

    【讨论】:

      【解决方案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.
          }
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-04
      • 2011-02-17
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多