2012-07-08 1 views
2

내 응용 프로그램에서 몇 가지 비교 방법이 있습니다. 나는 사용자가 사용할 정렬 방법을 선택할 수 있기를 바랍니다. 이상적으로는 대리자를 설정하고 사용자의 선택에 따라 업데이트됩니다. 이 방법을 사용하면 List.Sort (대리자)를 사용하여 코드를 일반으로 유지할 수 있습니다.List.Sort()에 대한 명명 된 대리자를 Comparison에 사용하는 방법?

이번이 처음으로 C# 대리자를 사용하려고 시도했지만 구문 오류가 발생했습니다. 여기에 지금까지 무엇을 가지고 :

대리인 : 클래스 생성자에서

private delegate int SortVideos(VideoData x, VideoData y); 
private SortVideos sortVideos; 

:

sortVideos = Sorting.VideoPerformanceDescending; 

내가 그것을 호출 할 때 작동하는 공공 정적 정렬 클래스의 비교 방법 (직접) :

public static int VideoPerformanceDescending(VideoData x, VideoData y) 
{ 
    *code statements* 
    *return -1, 0, or 1* 
} 

"일부 잘못된 인수"가 포함 된 구문 오류 :

videos.Sort(sortVideos); 

궁극적으로 "sortVideos"를 선택 방법을 가리 키도록 변경하고 싶습니다. "videos"는 VideoData 유형의 목록입니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

+0

쓰기? – hatchet

+0

어떤 오류가 발생합니까? – SLaks

답변

5

Comparison<T> 대리인을 허용하므로 자신의 대리인을 정의 할 수 없으므로 대리자 Comparison<T>을 다시 사용하기 만하면됩니다. 또한 사용자의 선택 부분을 찬찬히 대답을 확장

private static Comparison<VideoData> sortVideos; 

static void Main(string[] args) 
{ 
    sortVideos = VideoPerformanceDescending; 

    var videos = new List<VideoData>(); 

    videos.Sort(sortVideos); 
} 

, 당신은 사전에 사용할 수있는 옵션을 저장할 수 후 UI에 사용자가 사전에 키를 선택하여 정렬 알고리즘을 선택할 수 있습니다.

private static Dictionary<string, Comparison<VideoData>> sortAlgorithms; 

static void Main(string[] args) 
{ 
    var videos = new List<VideoData>(); 

    var sortAlgorithms = new Dictionary<string, Comparison<VideoData>>(); 

    sortAlgorithms.Add("PerformanceAscending", VideoPerformanceAscending); 
    sortAlgorithms.Add("PerformanceDescending", VideoPerformanceDescending); 

    var userSort = sortAlgorithms[GetUserSortAlgorithmKey()]; 

    videos.Sort(userSort); 
} 

private static string GetUserSortAlgorithmKey() 
{ 
    throw new NotImplementedException(); 
} 

private static int VideoPerformanceDescending(VideoData x, VideoData y) 
{ 
    throw new NotImplementedException(); 
} 

private static int VideoPerformanceAscending(VideoData x, VideoData y) 
{ 
    throw new NotImplementedException(); 
} 
+0

가장 빠른 정답입니다! 고맙습니다! – James

3

SortComparison<T> 대리자 형식이 아니라 당신의 SortVideos 대리자 형식을합니다.

위임 유형을 전혀 작성하지 않아야합니다.
대신에, 당신이`videos`의 선언을 보여줄 수

videos.Sort(SomeMethod); 
관련 문제