C# Generic "Generic Type"정의를 가진 "어디에 제약 조건"?
-
20-09-2019 - |
문제
예를 들어 보겠습니다.
일반 클래스/인터페이스 정의가 있습니다.
interface IGenericCar< T > {...}
위의 클래스와 관련하여 다른 클래스/인터페이스가 있습니다.
interface IGarrage< TCar > : where TCar: IGenericCar< (**any type here**) > {...}
기본적으로 나는 내 일반적인 igarrage가 IGenericCar
, 그럼에도 불구하고 IGenericCar<int>
또는 IGenericCar<System.Color>
, 나는 그 유형에 의존하지 않기 때문에.
해결책
일반적으로이를 달성하는 두 가지 방법이 있습니다.
옵션 1: 다른 매개 변수를 추가하십시오 IGarrage
대표 T
이를 전달해야합니다 IGenericCar<T>
강제:
interface IGarrage<TCar,TOther> where TCar : IGenericCar<TOther> { ... }
옵션 2: 기본 인터페이스를 정의합니다 IGenericCar<T>
이는 일반적인 것이 아니며 해당 인터페이스에 대한 제약
interface IGenericCar { ... }
interface IGenericCar<T> : IGenericCar { ... }
interface IGarrage<TCar> where TCar : IGenericCar { ... }
다른 팁
다음과 같은 일을하는 것이 합리적입니까?
interface IGenericCar< T > {...}
interface IGarrage< TCar, TCarType >
where TCar: IGenericCar< TCarType > {...}
제휴하지 않습니다 StackOverflow