Skip to main content
 首页 » 编程设计

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

2024年02月24日21kuangbin

有了结构..

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."); 
    } 
}