我明白 C# 中没有多重继承。但是,我遇到了一种我真的希望它存在的情况。我正在创建一个自定义类,它需要我从 CLR 类型继承并覆盖一些方法。不幸的是,我正在创建其中几个非常相似的。为了 DRY,我真的很想将通用功能移动到基类,但我需要从 2 个类继承。我可以使用接口(interface)(事实上我现在正在使用一个接口(interface))但这只解决了一半的问题,因为方法实现仍然需要在多个自定义类中重复。
实现我想要做的事情的最纯粹的方法是什么?
编辑:
这是一个通用的代码示例
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
}
最佳答案
有时我觉得多重继承可以挽救局面,但我意识到它确实使实现和可维护性更具挑战性。 MI 在继承的类中有效地合并了公共(public)和 protected 命名空间,这可能会导致一些您不需要的歧义和复杂性。
关于c# - C# : What is the purist way of achieving what I am trying to do? 中的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3195786/