【问题标题】:Explicit C# interface implementation of interfaces that inherit from other interfaces从其他接口继承的接口的显式 C# 接口实现
【发布时间】:2011-02-17 06:42:47
【问题描述】:

考虑以下三个接口:

interface IBaseInterface
{
    event EventHandler SomeEvent;
}

interface IInterface1 : IBaseInterface
{
    ...
}

interface IInterface2 : IBaseInterface
{
    ...
}

现在考虑以下实现 IInterface1 和 IInterface 2 的类:

class Foo : IInterface1, IInterface2
{
    event EventHandler IInterface1.SomeEvent
    {
        add { ... }
        remove { ... }
    }

    event EventHandler IInterface2.SomeEvent
    {
        add { ... }
        remove { ... }
    }
}

这会导致错误,因为 SomeEvent 不是 IInterface1 或 IInterface2 的一部分,它是 IBaseInterface 的一部分。

Foo 类如何同时实现 IInterface1 和 IInterface2?

【问题讨论】:

    标签: c# interface implementation explicit explicit-implementation


    【解决方案1】:
    interface IBaseInterface
    {
        event EventHandler SomeEvent;
    }
    
    interface IInterface1 : IBaseInterface
    {
        event EventHandler SomeEvent;
    }
    
    interface IInterface2 : IBaseInterface
    {
        event EventHandler SomeEvent;
    }
    
    class Foo : IInterface1, IInterface2
    {
    
        public event EventHandler SomeEvent
        {
            add { }
            remove { }
        }
    
        event EventHandler IInterface1.SomeEvent
        {
            add { }
            remove { }
        }
    
    
        event EventHandler IInterface2.SomeEvent
        {
            add { }
            remove { }
        }
    }  
    

    【讨论】:

      【解决方案2】:

      你可以使用泛型:

      interface IBaseInterface<T> where T : IBaseInterface<T>
      {
          event EventHandler SomeEvent;
      }
      
      interface IInterface1 : IBaseInterface<IInterface1>
      {
          ...
      }
      
      interface IInterface2 : IBaseInterface<IInterface2>
      {
          ...
      }
      
      class Foo : IInterface1, IInterface2
      {
          event EventHandler IBaseInterface<IInterface1>.SomeEvent
          {
              add { ... }
              remove { ... }
          }
      
          event EventHandler IBaseInterface<IInterface2>.SomeEvent
          {
              add { ... }
              remove { ... }
          }
      }    
      

      【讨论】:

      • 我喜欢你的短臂,先生。
      【解决方案3】:

      SomeEvent 不是 IInterface1 或 IInterface2 的一部分,它是 IBaseInterface 的一部分。

      class Foo : IInterface1, IInterface2
      {
          event EventHandler IBaseInterface.SomeEvent {
              add { ... }
              remove { ... }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-26
        • 1970-01-01
        • 2016-10-23
        • 2016-03-07
        • 1970-01-01
        • 1970-01-01
        • 2016-09-12
        • 2023-03-13
        相关资源
        最近更新 更多