C # inherit (kind off) / use properties of multiple classes in one class

Let's say I have 2 classes:

public class A
{
    public string P1{ get; set; }
    public string P2{ get; set; }
}

public class B
{
    public string P3{ get; set; }
    public string P4{ get; set; }
}

and I need a class:

public class C
{
    public string P1{ get; set; }
    public string P2{ get; set; }
    public string P3{ get; set; }
    public string P4{ get; set; }
}

Is it possible for class C to use class A and B instead of re-declaring all the properties?
(I need it for the DTO)

+3
source share
6 answers

You cannot , since multiple inheritance is only for C # interfaces.

Khaki

I:

public class C : { public A; public B; }

II:

public interface IA { string P1, P2; }    
public interface IB { string P3, P4; }

public class C : IA, IB { string P1, P2, P3, P4; }

III:

public class A { public string P1, P2; }
public class B : A { public string P3, P4; }

public class C : B {}

As for the DTO, perhaps these links are 1 ; 2 may be useful:

If not, you can build your class dynamically using reflection.

C, A, B.

+2

, #. A B, .

, , :

public class C

{

public A APart { get; set; }

public B BPart { get; set; }

}

+7

IA IB, A B , C . - C, , A B.

interface IA {
  string P1;
  string P2;
}

interface IB {
  string P3;
  string P4;
}

class A : IA {
  string P1 { get; set; }
  string P2 { get; set; }
}

class B : IB {
  string P3 { get; set; }
  string P4 { get; set; }
}

class C : IA, IB {
  string P1 { get; set; }
  string P2 { get; set; }
  string P3 { get; set; } 
  string P4 { get; set; }
}
+2

:

interface IA { 
  string P1; 
  string P2; 
} 

interface IB { 
  string P3; 
  string P4; 
} 

class A : IA { 
  string P1 { get; set; } 
  string P2 { get; set; } 
} 

class B : IB { 
  string P3 { get; set; } 
  string P4 { get; set; } 
} 

class C : IA, IB { 
  private IA a;
  private IB b;
  string P1 { get { return a.P1; } set { a.P1 = value } } 
  string P2 { get { return a.P2; } set { a.P2 = value } } 
  string P3 { get { return b.P3; } set { b.P3 = value } } 
  string P4 { get { return b.P4; } set { b.P4 = value } }
} 

, .

+1

, B A, C B.

0

, . Unline , .

0
source

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


All Articles