Why is it not allowed to explicitly implement basic interface methods on a derived interface?

This is a simplified example to explain my problem. I'm trying to improve the readability of the code to explicitly implemented a common interface, moving a common interface to interface with a particular type, like this: interface ITyped : IGeneric<string>. The idea is to not use IGeneric<string>in all implemented explicit method names.

So the code will read:

ITyped.M1(string p){}
ITyped.M2(string p){} 

instead

IGeneric<string>.M1(string p){}
IGeneric<string>.M2(string q){}

Introduce an interface with several generic types to understand why I'm trying to do this.

Now the fact is that this will not work! The compiler throws an error, so my declaration is not a member of the interface. I have to explicitly use the base interface with a generic declaration. Wouldn't that make sense if it worked? Further attempts showed that not even a generic is required - a simple derived interface also does not allow explicitly implementing the inherited method of the base interface in the derived interface. I would like to understand the theory why it was forbidden.

Is there an alternative to improve readability for this scenario?

Example code:

interface IGeneric<T>
{
    void M(T t);
}

interface ITyped: IGeneric<string> { }

class C : ITyped
{
    //Explicit declaration with base interface - OK
    void IGeneric<string>.M(string t) {}

    //Implicit declaration - OK
    public void M(string t){ }

    //Explicit declaration with derived interface - Error!
    void ITyped.M(string t) {} //Error CS0539   

}
+4
source share
2 answers

After hinting at the C # language specification and CodesInChaos comment on another answer, I was able to find a reason why it would not be allowed:

IDerived2: IBase , ,

private interface IBase
{
    void M();
}

class C : IDerived1, IDerived2
{
    //Which method should now be called when using IBase.M?
    void IDerived1.M() {} 
    void IDerived2.M() {}  
}

, , . , , - .

, - , , .

+2

:

IGeneric<string> x = new C();

C M IGeneric<T>, , .

-2

Source: https://habr.com/ru/post/1625357/


All Articles