能不能帮我把程序编译一下, 通不过, 但是不知道是什么错误
?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace TestGenerics
{
public class Book : IComparable
{
private int id;
private string title;
public Book() { }
public Book(int id, string title)
{
this.id = id;
this.title = title;
}
public int Id
{
get { return id; }
set { id = value; }
}
public string Title
{
get { return title; }
set { title = value; }
}
public int CompareTo(object obj)
{
Book book2 = (Book)obj;
return this.Id.CompareTo(book2.Id);
}
}
public class SortHelper<T> where T : IComparable<T>
{
public void BubbleSort(T[] array)
{
int length = array.Length;
for (int i = 0; i <= length - 2; i++)
{
for (int j = length - 1; j >= 1; j--)
{
// 对两个元素进行交换
if (array[j].CompareTo(array[j - 1]) < 0)
{
T temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
Book[] bookArray = new Book[2];
bookArray[0] = new Book(123, "wangnuo");
bookArray[1] = new Book(456, "chen");
SortHelper<Book> sorter = new SortHelper<Book>();
sorter.BubbleSort(bookArray);
foreach(Book b in bookArray)
{
Console.WriteLine("Id : {0}", b.Id);
Console.WriteLine("Tile : {0}", b.Title);
}
}
}
}
谢谢各位大神了!!
将public class SortHelper<T> where T : IComparable<T>改成public class SortHelper<T> where T : Book,见下图:
谢谢 不过 为什么呢?
Book要实现IComparable<Book>接口。
这样的话 不就会出现一个异常么
@诺-诺: 为什么会出现异常呢,你实现这个接口的方法就行了啊。