Skip to main content
 首页 » 编程设计

c#之需要抽象对象集合 (C#)

2024年01月29日32开发

在下面的简化示例中,我需要以 PrintFruitsAndEaters(oranges, orangeEaters); 或 PrintFruitsAndEaters(apples, appleEaters); 的方式抽象 Collection 类 成为可能:

abstract class Fruit 
abstract class FruitEater 
 
class Apple : Fruit 
class AppleEater : FruitEater 
class Orange : Fruit 
class OrangeEater : FruitEater 
 
class AppleCollection : List<Apple> 
class OrangeCollection : List<Orange> 
class AppleEaterCollection : List<AppleEater> 
class OrangeEaterCollection : List<OrangeEater> 

我已尝试将方法和集合类模板化,但我需要访问特定于 Fruit 和 FruitEater 类的方法:

class FruitCollection<T> : List<T> 
class FruitEaterCollection<T> : List<T> 
 
void PrintFruitsAndEaters<T, S>(FruitCollection<T> fruits, FruitEaterCollection<S> eaters) 

请您参考如下方法:

那么你想要这个:

void PrintFruitsAndEaters<T, S>( 
    FruitCollection<T> fruits, 
    FruitEaterCollection<S> eaters) 
        where T : Fruit 
        where S : FruitEater 
{ 
    // ... 
} 

这将限制 T和 S根据需要输入;使用 FruitCollection<T> 调用方法, 其中T不能保证是 Fruit或子类型,将导致编译时错误。与 S 相同和 FruitEater .

由于约束,当使用 T 类型的值时您将能够访问 Fruit 的成员类,并且在使用 S 类型的值时您将能够访问 FruitEater 的成员类。

请注意,根据 Brian(已删除)的回答,您可能还想为集合类型添加约束:

class FruitCollection<T> : List<T> where T : Fruit { } 
class FruitEaterCollection<T> : List<T> where T : FruitEater { } 

但是这仍然不允许您忽略对方法的约束。

(此外,继承 List<T> 是一件坏事,请改用 IList<T> )