Explicit C# interface implementation of interfaces

2019-06-24 06:14发布

Consider the following three interfaces:

interface IBaseInterface
{
    event EventHandler SomeEvent;
}

interface IInterface1 : IBaseInterface
{
    ...
}

interface IInterface2 : IBaseInterface
{
    ...
}

Now consider the following class that implements both IInterface1 and IInterface 2:

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

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

This results in an error because SomeEvent is not part of IInterface1 or IInterface2, it is part of IBaseInterface.

How can the class Foo implement both IInterface1 and IInterface2?

3条回答
不美不萌又怎样
2楼-- · 2019-06-24 06:39

You can use generics:

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楼-- · 2019-06-24 06:49
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 { }
    }
}  
查看更多
Evening l夕情丶
4楼-- · 2019-06-24 07:03

SomeEvent isn't part of IInterface1 or IInterface2, its a part of IBaseInterface.

class Foo : IInterface1, IInterface2
{
    event EventHandler IBaseInterface.SomeEvent {
        add { ... }
        remove { ... }
    }
}
查看更多
登录 后发表回答