c# - 在使用泛型继承类中实现加法

标签 c# generics inheritance language-features

有了结构..

abstract class Unit
{
 int Id;
}

class Measure : Unit
{
 int Current;
 int Baseline;
}

class Weight : Unit
{
 int Minimum;
 int Maximum;
 int Current;
}

我基本上想添加一个“添加”方法,例如将两个度量加在一起,或者将两个权重加在一起。但它需要在 Unit 基类中。所以基本上如果我有

List<Units> units = new List<Unit>();
List<Units> otherUnits = new List<Unit>();

// populate units with various Measures and Weights.
// populate otherUnits with various Measures and Weights.
foreach(Unit u in units)
{
 u.Add( 
         // add something from the otherUnits collection. Typesafe, etc.
      ); 
} 

我试过了..

public abstract T Add<T>(T unit) where T : Unit;

在 Unit 类中,但是当我尝试用适当的类填充“T”时,我得到关于它不是继承类中适当标识符的错误。有什么想法吗?

最佳答案

您需要更改您的 Unit 抽象类以采用通用类型:

abstract class Unit<T>

然后你可以添加Add抽象方法:

void Add(T unit);

所以您的测量和体重等级现在看起来像:

class Measure : Unit<Measure>
class Weight : Unit<Weight>

或者,将以下抽象方法添加到Unit:

abstract void Add(Unit unit);

然后您需要在您的继承类中使用类型检查来限制它:

void Add(Unit unit)
{
    if (unit.GetType() != this.GetType())
    {
        throw new ArgumentException("You can only add measurements.");
    }
}

关于c# - 在使用泛型继承类中实现加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3639098/

相关文章:

c# - 将通用实例转换为基类

c# - 为什么通用 EventHandler<TArgs> 未得到充分利用?

java - 面向对象设计: class inherit class that contains field of class that inherit another class

C#、Windows 窗体、LinkLabel 列

c# - 实时捕获用户输入错误

c# - 我可以加快从 C++ Dll 到 C# 的回调吗?

java - 泛型中的通配符不起作用

c++ - 不处理指针时调用子类(虚拟)函数(后期绑定(bind))

android - 是否可以在 AIDL 接口(interface)中使用继承?

c# - 如何在 ASP.NET MVC 中创建两列蛇形布局?