2009-05-29 5 views
0

다른 형식의 일반 목록을 매개 변수로 사용하는 메서드를 오버로드하려면 어떻게해야합니까? 예를 들어다른 형식의 일반 목록을 매개 변수로 사용하는 메서드 오버로드

:

private static List<allocations> GetAllocationList(List<PAllocation> allocations) 
{ 
    ... 
} 

private static List<allocations> GetAllocationList(List<NPAllocation> allocations) 
{ 
    ... 
} 

내가 하나에이 두 방법을 결합 할 수있는 방법이 있나요 :

그래서 같은 두 가지 방법이 있나요?

답변

4

제네릭을 사용하면 확실히 할 수 있습니다!

private static List<allocations> GetAllocationList<T>(List<T> allocations) 
    where T : BasePAllocationClass 
{ 

} 

은 가정 당신의 "할당", "PAllocation"와 "NPAllocation" "BasePAllocationClass"라고 모두가 공유 몇 가지 기본 클래스. 그렇지 않으면 "where"제약 조건을 제거하고 유형 검사를 직접 수행 할 수 있습니다.

+0

,하지만 난 유형 검사를하는 것에 대해 어떻게 가야합니까? 또한 allocations 매개 변수를 반복해야합니다. allocations.ForEach (대리자 (PAllocation PA) {...});를 사용하려고했습니다. 호환되지 않는 익명의 함수 서명이라는 오류가 나타납니다. 어떤 아이디어? – Jon

+0

당신은 할 수 없어 (foreach var 할당)? – womp

1

PAllocation과 NPAllocation이 공통 인터페이스 또는 기본 클래스를 공유하는 경우 해당 기본 객체의 목록 만 허용하는 메소드를 만들 수 있습니다.

그러나 두 가지 (또는 그 이상) 방법을 하나로 결합하려는 경우 제네릭을 사용하여 수행 할 수 있습니다. 메소드 선언했다 경우 같은 :

private static List<allocations> GetCustomList<T>(List<T> allocations) 
{ 
    ... 
} 

은 당신은 사용하여 호출 할 수 있습니다 : 나는 당신의 제안을 사용하고

GetCustomList<NPAllocation>(listOfNPAllocations); 
GetCustomList<PAllocation>(listOfPAllocations); 
+0

유형이 자동으로 유추되기 때문에 부분을 생략 할 수 있습니다. – configurator

관련 문제