C # Interfaces and Type of Disguise

My subclasses cannot seem to disguise themselves as a base class when meeting interface requirements. For instance:

class MyBaseClass
{}

class MySubClass : MyBaseClass
{}

interface MyInterface
{
    MyBaseClass someFunction();
}

class MyImplementation : MyInterface
{
    public MySubClass someFunction() { return null; }
}

It raises the following error:

'MyNamespace.MyImplementation' does not implement a member of the interface 'MyNamespace.MyInterface.someFunction ()'. 'MyNamespace.MyImplementation.someFunction ()' cannot implement 'MyNamespace.MyInterface.someFunction ()' because it does not have the corresponding return type 'MyNamespace.MyBaseClass'.

This is also a problem with the requirements of interfaces and implementations. For example, if I have an interface with a function that returns an IList, my implementation cannot return a List - it MUST return an IList.

Am I doing something wrong or is this a limitation of C # interfaces?

+3
4

# . , . , , . :

class MyImplementation : MyInterface
{
    MyBaseClass MyInterface.someFunction() { return null; }
    public MySubClass someFunction() { return null; }
}
+4

, :

class MyImplementation : MyInterface
{
    public MyBaseClass someFunction() { return null; }
}

, :

interface MyInterface<T>
{
    T someFunction();
}

class MyImplementation : MyInterface<MySubClass>
{
    public MySubClass someFunction() { return null; }
}

. , - , MyInterface.someFunction

+2

MyBaseClass, . MySubClass , .

+1

MyImplementation ; , MySubClass, , MyBaseClass, , .

The same applies to your List / IList example, I cannot understand why you consider it weak.

0
source

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


All Articles