Why should I specify all type type parameters?

Is there any (technical) reason why C # requires all type parameters to be declared with the names of their enclosing classes?

For example, I would like to declare this:

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

public class AppleCollection : FruitCollection<Apple> { }
public class TomatoCollection : FruitCollection<Tomato> { }

TFruitis IFood<TFoodGroup>, therefore, TFoodGroupshould be determined if TFruitprovided, although I did not explicitly declare it.

Instead, I have to do this:

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

The second method works very well and prevents the compilation of any invalid combinations, but it gets confused as more and more unnecessary type declarations are added to the parameter list.


Other definitions in the set:

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 { }
+3
source share
1 answer

Suppose I define:

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

FruitCollection<Wompom>?

:

  • .
  • , .
+6

Source: https://habr.com/ru/post/1702772/


All Articles