2

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

这是我第一次尝试使用 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 类型的列表。我究竟做错了什么?

4

2 回答 2

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);
}

扩展答案以考虑用户选择部分,您可以将可用选项存储在字典中,然后在 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();
}
于 2012-07-08T21:43:27.207 回答
3

Sort接受Comparison<T>委托类型,而不是您的SortVideos委托类型。

您根本不应该创建委托类型。
相反,只需写

videos.Sort(SomeMethod);
于 2012-07-08T21:43:36.607 回答