Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit C# interface implementation of interfaces that inherit from other interfaces

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?

like image 591
anthony Avatar asked May 09 '10 00:05

anthony


People also ask

What is explicit C?

The explicit function specifier controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are conversion constructors.

What is explicit QT?

Explicit means, in this case, that a QWidget* cannot be implicitly converted to a MainWindow object. The :QMainWindow(parent) simply says that the base class constructor which takes a QWidget* as parameter should be called to construct the object.

What is implicit constructor in C++?

implicit constructor is a term commonly used to talk about two different concepts in the language, the. implicitly declared constructor which is a default or copy constructor that will be declared for all user classes if no user defined constructor is provided (default) or no copy constructor is provided (copy).

Can default constructor be explicit?

A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value initialization (8.5). It goes on to provide an example of an explicit default constructor, but it simply mimics the example I provided above.


1 Answers

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 { ... }
    }
}    
like image 197
Dylon Avatar answered Oct 05 '22 05:10

Dylon