2009-02-05 3 views
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> { } 

TFruitIFood<TFoodGroup>, 그래서 TFoodGroupTFruit가 제공되는 경우를 정의해야합니다, 내가 명시 적으로 선언되지 않은 경우에도.

대신,이 작업을 수행해야합니다 :

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

답변

6

나는 정의한다고 가정

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

FruitCollection<Wompom> 무엇을 의미?

모든 명시 적으로 지정하는 경우 :

  • 하는 컴파일러가 많은 복잡한 추론을 수행 할 필요가 없습니다
  • 언어는
  • 당신은 할 수없는 많은 복잡한 규칙을 수행 할 필요가 없습니다 이상한, 불가능한 상황에 빠지다
관련 문제