如何使用命名委托给List.Sort()的比较?

Jam*_*mes 2 c# delegates

在我的应用程序中,我有几种比较方法.我希望用户能够选择要使用的排序方法.理想情况下,我想设置一个委托,它会根据用户的选择进行更新.这样,我可以使用List.Sort(委托)保持代码的通用性.

这是我第一次尝试使用C#委托,而且我遇到了语法错误.这是我到目前为止:

代表:

private delegate int SortVideos(VideoData x, VideoData y);
private SortVideos sortVideos;
Run Code Online (Sandbox Code Playgroud)

在类构造函数中:

sortVideos = Sorting.VideoPerformanceDescending;
Run Code Online (Sandbox Code Playgroud)

public static Sorting类中的比较方法(当我直接调用它时可以工作):

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

抱怨"一些无效参数"的语法失败:

videos.Sort(sortVideos);
Run Code Online (Sandbox Code Playgroud)

最后,我想改变"sortVideos"来指出选择的方法."videos"是VideoData类型的列表.我究竟做错了什么?

Joã*_*elo 5

List<T>接受类型的委托Comparison<T>,所以你不能定义自己的委托,你只需要重用的委托Comparison<T>.

private static Comparison<VideoData> sortVideos;

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

    var videos = new List<VideoData>();

    videos.Sort(sortVideos);
}
Run Code Online (Sandbox Code Playgroud)

扩展答案以考虑用户选择部分,您可以将可用选项存储在字典中,然后在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();
}
Run Code Online (Sandbox Code Playgroud)