c# - 使用泛型类型的问题我的 C# 课
问题描述
书类
class Book : IComparable<Book>
{
public string ISBN;
public string Title;
public string Author;
public Book(string ISBN, string Title, String Author)
{
this.ISBN = ISBN;
this.Title = Title;
this.Author = Author;
}
public override string ToString()
{
return Title + " by " + Author + " ISBN: " + ISBN;
}
}
我的快速排序
这不会接受我的书类作为有效的数据类型
private static void QuickSort<T>(T[] items, int left, int right) where T: IComparable
{
int i, j;
i = left; j = right;
T pivot = items[left];
while (i <= j)
{
for (; (items[i].CompareTo(pivot)<0) && (i.CompareTo(right)<0); i++) ;
for (; (pivot.CompareTo(items[j]) < 0) && (j.CompareTo(left) > 0); j--) ;
if (i <= j)
swap(ref items[i++], ref items[j--]);
}
if (left < j) QuickSort<T>(items, left, j);
if (i < right) QuickSort<T>(items, i, right);
}
主要的
用于调用分拣机
static void Main(string[] args)
{
string[] array1 = { "Fred", "Zoe", "Angela", "Umbrella", "Ben" };
string[] titles = {"Writing Solid Code",
"Objects First","Programming Gems",
"Head First Java","The C Programming Language",
"Mythical Man Month","The Art of Programming",
"Coding Complete","Design Patterns",
"ZZ"};
string[] authors ={ "Maguire", "Kolling", "Bentley", "Sierra", "Richie", "Brooks", "Knuth", "McConnal", "Gamma", "Weiss" };
string[] isbns = { "948343", "849328493", "38948932", "394834342", "983492389", "84928334", "4839455", "21331322", "348923948", "43893284", "9483294", "9823943" };
Book[] library = new Book[10];
//add books in the array
for (int i = 0; i < library.Length; i++)
{
library[i] = new Book(isbns[i], titles[i], authors[i]);
}
当试图对我的课本图书馆进行排序时,代码将不接受书籍作为IComparable
QuickSort(library, 0, library.Length - 1);
Console.Write(Environment.NewLine);
解决方案
您的 QuickSort 类指定T
必须实现IComparable
IComparable
(non-generic) 与IComparable<T>
(generic) 不同,因此如果您更改为它,它将起作用:
private static void QuickSort<T>(T[] items, int left, int right)
where T: IComparable<T>
推荐阅读
- python - 使用全局变量时,函数返回错误“NameError: name 'context_word' is not defined”
- html - 如何在A4页面内点击打印大小票据?
- vb.net - 使用 Assembly.load() (vb.net) 导入 DLL 的方法
- excel - 如何创建循环以从列表中获取数据并将其复制到相应的工作表中?
- postgresql - Postgresql 数组唯一聚合
- javascript - ReactJS:一个组件有两种不同的样式
- html - 如何对齐多个
- r - 消除数据集中的特定行
- python - 如何在python中启动并行进程?
- c# - 如何为结果进行等待异步任务以进一步操作 xamarin 表单?