제네릭 및 인터페이스 열거
-
10-07-2019 - |
문제
모두 인터페이스를 구현하는 클래스 세트가있는 경우
interface IMyinterface<T>
{
int foo(T Bar);
}
나는 그들 모두를 목록에 밀어 넣고 그들을 통해 열거하고 싶다.
List<IMyinterface> list
foreach(IMyinterface in list)
// etc...
그러나 컴파일러는 T가 무엇인지 알고 싶어합니다. 이걸 할 수 있나요? 이 문제를 어떻게 극복 할 수 있습니까?
해결책
iMyinterface 유형이 없습니다. 유형 인수가 필요한 iMyinterface`1 유형 만 있습니다. iMyinterface 유형을 만들 수 있습니다.
interface IMyinterface { ... }
그런 다음 상속합니다
interface IMyinterface<T> : IMyinterface { ... }
Foreach 루프에서 사용하려는 멤버를 IMyinterface 정의로 옮겨야합니다.
다른 팁
서명에서 t로 메소드를 호출하려는 경우 답은 할 수 없다는 것입니다. 그렇지 않으면 Anthonywjones가 제안한대로 할 수 있습니다
여전히 컴파일러에게 어떤 시간이 무엇인지 알려 주어야하지만, 요청한 일은 다음과 같습니다.
interface IMyinterface
{
int foo<T>(T Bar);
}
List<IMyinterface> list = new List<IMyinterface>();
foreach(IMyinterface a in list){}
제휴하지 않습니다 StackOverflow