开发者

Combine the functions of two different base classes

I'm trying to combine the functions of two different base classes into a new class, to no avail. Say I have class A and B, whereas B is a descendant of A with different functionality (i.e. can't be used as a substitute for A during runtime) and need a开发者_运维问答 class C, which combines A and B, uses both and provides a unique interface to users of C. How can I achieve this? Multiple inheritance isn't possible with C#, interfaces don't seem to fit. So what can I do?


Your design is broken.

B is a descendant of A with different functionality (i.e. can't be used as a substitute for A during runtime)

That situation is a mis-use of inheritance. If you want to do that, you should either use composition or a common interface that both A & B implement separately instead.


Consider explicit interface implementation:

http://msdn.microsoft.com/en-us/library/ms173157.aspx

public interface IFriendly
{
  void Greet();
}

public interface IEnemy
{
  void Greet();
}

public class SomeGuy : IFriendly, IEnemy
{
  //default Greeting
  public void Greet()
  {
    //...
  }

  //greeting when using an IFriendly reference
  void IFriendly.Greet()
  {
    //,,
  }

  //greeting when using an IEnemy reference
  void IEnemy.Greet()
  {
    //,,
  }
}


You say that B descends from A but is different and cannot be used as an A; this defies the purpose of inheritance altogether. What are you trying to achieve? Regardless, it sounds as though you should be using composition, not inheritance. If C does not expose the interface defined by A or B, then it should not inherit from either.


The fact that you need to consider such an action makes me think that you might need to consider refactoring your class structure.

But, to solve your immediate problem why not instantiate the two classes (ignore the fact that they are in an inheritance relationship) and call the methods in the sequence you need? Think of C as a facade pattern for A and B.


Problem solved. Using System.Reflection now.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜