我确实理解C#中没有多重继承.但是,我遇到了一种我真的希望它存在的情况.我正在创建一个自定义类,它要求我继承CLR类型并覆盖一些方法.不幸的是,我正在创建其中几个非常相似的.为了DRY的利益,我真的想将常用功能移到基类,但后来我需要继承2个类.我可以使用接口(事实上我现在正在使用它)但这只解决了一半的问题,因为方法实现仍然需要在几个自定义类中重复.
实现我想要做的事情的纯粹方式是什么?
编辑:
这是一个通用的代码示例
public class CustomTypeOne : CLRType
{
public override void Execute(HttpContext context)
{
//Some code that's similar across CustomTypeOne, CustomTypeTwo etc
}
public void DoStuff()
{
//Same for all CustomTypes and can be part of a base class
}
//More methods
}
public class CustomTypeTwo : CLRType
{
public override void Execute(HttpContext context)
{
//Some code that's similar across CustomTypeOne, CustomTypeTwo etc
}
public void DoStuff()
{
//Same for all CustomTypes and can be part of a base class
}
//More methods
}
Run Code Online (Sandbox Code Playgroud)
有几种方法可以实现您所说的内容。
假设你有一个像这样的结构
MyTypeA : CLR_TypeA
{
public override ToString()
{
//do some complicated stuff
}
}
MyTypeB : CLR_TypeB
{
public override ToString()
{
//do the same complicated stuff
}
}
Run Code Online (Sandbox Code Playgroud)
那么想要有一个基类是有道理的,但你不能。其他答案提到的一种方法是组合。但是,在您的情况下,可能可以创建另一个静态类
public static class ToStringHelpers
{
public static DoComplicatedStuff()
{
//do some pretty wild stuff.
}
}
MyTypeA : CLR_TypeA
{
public override ToString()
{
DoComplicatedStuff();
}
}
MyTypeB : CLR_TypeB
{
public override ToString()
{
DoComplicatedStuff();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,所有需要重复功能的不同对象都可以调用辅助方法。在这种情况下,多重继承的唯一优点是您不必一遍又一遍地编写“DoComplicatedStuff()”,但复制/粘贴无论如何都会很快解决该问题。
如果您从同一类型继承,则不需要 MI
MyBaseType : CLRType
{
public override void Execute(HttpContext context)
{
//Some code that's similar across CustomTypeOne, CustomTypeTwo etc
}
public void DoStuff()
{
//Same for all CustomTypes and can be part of a base class
}
}
MyTypeA : MyBaseType
{
public void MyTypeACustomMethod()
{
//do class specific logic here
}
}
MyTypeB : MyBaseType
{
public void MyTypeBCustomMethod()
{
//do class specific logic here
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
396 次 |
| 最近记录: |