3
C#에서 모든 제네릭 형식 매개 변수를 둘러싸는 클래스 이름과 함께 선언해야하는 기술적 인 이유가 있습니까?모든 제네릭 형식 매개 변수를 지정해야하는 이유는 무엇입니까?
예를 들어,이 선언 싶습니다
public class FruitCollection<TFruit> : FoodCollection<TFoodGroup>
where TFruit : IFood<TFoodGroup>
where TFoodGroup : IFoodGroup { }
public class AppleCollection : FruitCollection<Apple> { }
public class TomatoCollection : FruitCollection<Tomato> { }
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> { }
두 번째 방법은 잘 작동하고 컴파일에서 유효하지 않은 조합을 방지 할 수 있지만 점점 더 불필요한 일반적인 유형 선언이 매개 변수에 추가로 더러워지고 시작 명부. 세트의
다른 정의는 다음과 같습니다
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 { }