为什么我必须指定所有泛型类型参数?

ajl*_*ane 3 c# generics

有没有(技术)原因,C#要求所有泛型类型参数与它们的封闭类名称一起声明?

例如,我想声明这个:

public class FruitCollection<TFruit> : FoodCollection<TFoodGroup>
    where TFruit : IFood<TFoodGroup>
    where TFoodGroup : IFoodGroup { }

public class AppleCollection : FruitCollection<Apple> { }
public class TomatoCollection : FruitCollection<Tomato> { }
Run Code Online (Sandbox Code Playgroud)

TFruit是一个IFood<TFoodGroup>,所以TFoodGroup 必须定义,如果TFruit提供,即使我没有明确声明它.

相反,我必须这样做:

public class FruitCollection<TFoodGroup, TFruit> : FoodCollection<TFoodGroup>
    where TFruit : IFood<TFoodGroup>
    where TFoodGroup : IFoodGroup { }

// Anything other than FruitGroup is an error when combined with Apple
public class AppleCollection : FruitCollection<FruitGroup, Apple> { }

// Anything other than VegetableGroup is an error when combined with Tomato
public class TomatoCollection : FruitCollection<VegetableGroup, Tomato> { }
Run Code Online (Sandbox Code Playgroud)

第二种方法可以正常工作并防止任何无效组合编译,但随着越来越多的不必要的泛型类型声明被添加到参数列表中,它开始变得混乱.


该集合中的其他定义是:

public interface IFoodGroup { }
public class FruitGroup : IFoodGroup { }
public class VegetableGroup : IFoodGroup { }

public interface IFood<TFoodGroup> where TFoodGroup : IFoodGroup { }
public class Apple : IFood<FruitGroup> { }
public class Tomato : IFood<VegetableGroup> { }

public abstract class FoodCollection<TFoodGroup> where TFoodGroup : IFoodGroup { }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

假设我定义:

public class Wompom : IFood<VegetableGroup>, IFood<FruitGroup>
{
}
Run Code Online (Sandbox Code Playgroud)

什么FruitCollection<Wompom>意思?

明确指定所有内容时:

  • 编译器不必执行那么复杂的推理
  • 该语言不必执行许多复杂的规则
  • 你不能陷入许多奇怪的,不可能的情况