首页 新闻 赞助 找找看

我在泛型的这块遇到了一点问题求解

0
悬赏园豆:5 [已解决问题] 解决于 2015-08-31 17:39

能不能帮我把程序编译一下, 通不过, 但是不知道是什么错误

 

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

 

 

谢谢各位大神了!!

诺-诺的主页 诺-诺 | 初学一级 | 园豆:161
提问于:2015-08-31 17:17
< >
分享
最佳答案
1

将public class SortHelper<T> where T : IComparable<T>改成public class SortHelper<T> where T : Book,见下图:

收获园豆:4
猛士 | 初学一级 |园豆:8 | 2015-08-31 17:37

谢谢   不过  为什么呢?

诺-诺 | 园豆:161 (初学一级) | 2015-08-31 17:39
其他回答(1)
0

Book要实现IComparable<Book>接口。

收获园豆:1
SuperJoe | 园豆:68 (初学一级) | 2015-08-31 17:32

这样的话  不就会出现一个异常么

支持(0) 反对(0) 诺-诺 | 园豆:161 (初学一级) | 2015-08-31 17:36

@诺-诺: 为什么会出现异常呢,你实现这个接口的方法就行了啊。

支持(0) 反对(0) SuperJoe | 园豆:68 (初学一级) | 2015-08-31 17:41
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册