首页 > 解决方案 > 使用泛型类型的问题我的 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);

标签: c#typesicomparable

解决方案


您的 QuickSort 类指定T必须实现IComparable

IComparable(non-generic) 与IComparable<T>(generic) 不同,因此如果您更改为它,它将起作用:

private static void QuickSort<T>(T[] items, int left, int right) 
        where T: IComparable<T>

推荐阅读