开发者

C# inherit(kind off)/use the properties of multiple classes in a single class

Let's say I have 2 classes like this:

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 like this:

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

it it possible for the class C to use class A and 开发者_开发知识库B instead of re-declaring all the properties ?

(I need this for DTOs)


No, multiple inheritance is not supported in C#. It can either use A or B, not both.

This is doable, but maybe not pretty:

public class C
{
   public A APart { get; set; }

   public B BPart { get; set; }
}


You can't, as multiple inheritance is only for interfaces in C#.

Hacks

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, maybe these links 1; 2 could be useful:

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

Build dynamically a new C class containing all the public properties of both A and B.


You could define interfaces IA and IB which A and B both implement and both of which C implements. The fields still need to be declared in C but they are checked at compile time to ensure parity with A and 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; }
}


How about you combine the answers above:

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 } }
} 

Not super pretty or easy to generate, but it should retain data ownership and class relations.


Not unless you make B inherit from A and then let C inherit from B.


Nope, the solution is to use interfaces. Unline multiple inherritance it doesn't give you automagicness of implementation but it does provide polymorphism and compile time type safety.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜