Can I implement an interface using a subclass in C #?

considering the following:

class A : B {}

interface I
{
 B TheObject {get;set;}
}

Can I do it somehow?

class C : I
{
 public A TheObject {get;set;} 
}

Note that the interface has a base class, and the implementation has a subclass.

+3
source share
7 answers

Try

class C : I
{
 public A TheObject {get;set;} 
 B I.TheObject 
 {
   get { return A; }
   set { A = value as A; }
 }
}

You may need to change the installer B, depending on your needs. Implementing an interface in this way has the following consequences. When working with a variable printed as C, you will not be able to access the B object. If you need to, you will need to declare the variable i and assign it to your variable C var. The implementation of I is thus known as the explicit implementation.

eg,

C c = new C();
A a = c.TheObject; // TheObject is an A
I i = c;
B b = i.TheObject;
+11
source

, . , , ( ). , A C...

public class C : I
{
  public B TheObject { get { return new A(); } set {} }
}
+2

, . , # 4.0. /.

+1

. .

, : , . , .

+1

, :

class D : B {}

C c = new C();
c.TheObject = new D(); // error. D is not A, A is not D

D , I, , TheObject C D. , D A . , , , , , A . A D, A D B.

.

P.S. Troels Knak-Nielsen , .

+1

, , /, # 4.0 . - , .

, A B, , A, TheObject B. , , /. # 4.0.

0

:

class B { }

class A : B { }

interface I<T> where T : B
{
    T TheObject { get; set; }
}

class C : I<A>
{
    public A TheObject { get; set; }
}

, , ?

0

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


All Articles