从其他接口继承的接口的显式 C# 接口实现

ant*_*ony 5 c# implementation explicit interface explicit-implementation

考虑以下三个接口:

interface IBaseInterface
{
    event EventHandler SomeEvent;
}

interface IInterface1 : IBaseInterface
{
    ...
}

interface IInterface2 : IBaseInterface
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

    event EventHandler IInterface2.SomeEvent
    {
        add { ... }
        remove { ... }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Chr*_*ers 5

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

class Foo : IInterface1, IInterface2
{
    event EventHandler IBaseInterface.SomeEvent {
        add { ... }
        remove { ... }
    }
}
Run Code Online (Sandbox Code Playgroud)


Dyl*_*lon 5

您可以使用泛型:

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 { ... }
    }
}    
Run Code Online (Sandbox Code Playgroud)