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

时间:2009-02-05 17:36:49

标签: 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> { }

TFruitIFood<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> { }

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


集合中的其他定义是:

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 { }

1 个答案:

答案 0 :(得分:6)

假设我定义:

public class Wompom : IFood<VegetableGroup>, IFood<FruitGroup>
{
}

FruitCollection<Wompom>意味着什么?

明确指定所有内容时:

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