无法创建类的唯一实例

时间:2016-06-10 00:59:32

标签: c# class sorting instance

我一直致力于实现不同排序方法的类。 myTest.bubblesort(sortMe, false)按升序返回排序列表。我检查过这种行为它运行正常。 backTest.bubblesort(sortMe, true)返回按降序排序的相同列表。我检查这种行为是否正确。

我遇到麻烦的地方是backTest TestSorting实例的行为就像是对myTest实例的引用。更改backTest对象时,它还会修改myTest对象。换句话说,它们不像我预期的那样是唯一的实例。有人可以解释原因吗?

class Program
{
    static void Main(string[] args)
    {
        int[] sortMe = Sorting.GenerateTestArray(10, 100);
        TestSorting<int> myTest = new TestSorting<int>();
        TestSorting<int> backTest = new TestSorting<int>();
        int[] test = myTest.BubbleSort(sortMe, false);
        int[] testBack = backTest.BubbleSort(sortMe, true);
    }
}

class TestSorting<T> where T : IComparable
    {
       public T[] BubbleSort(T[] sortMe, bool descending)
        {
            if (!descending)
                return BubbleAscending(sortMe);

            else
                return BubbleDescending(sortMe);
        }

        private T[] BubbleAscending(T[] sortMe) 
        {
            bool stopMe = true;
            int stopRecurse = sortMe.Length - 1;
            int optimizeMe = stopRecurse;

            for (int i = 0; i < stopRecurse && stopMe; i++)
            {
                stopMe = false;

                for (int j = 0; j < optimizeMe; j++)
                {
                    if (sortMe[j].CompareTo(sortMe[j + 1]) > 0)
                    {
                        Swap(sortMe, j, j + 1);
                        stopMe = true;
                    }
                }

                optimizeMe--;
            }

            return sortMe;
        }

        private T[] BubbleDescending(T[] sortMe)
        {
            bool stopMe = true;
            int stopRecurse = sortMe.Length - 1;
            int optimizeMe = 0;

            for (int i = 0; i < stopRecurse && stopMe; i++)
            {
                stopMe = false;

                for (int j = stopRecurse; j > optimizeMe; j--)
                {
                    if (sortMe[j].CompareTo(sortMe[j - 1]) > 0)
                    {
                        Swap(sortMe, j, j - 1);
                        stopMe = true;
                    }
                }

                optimizeMe++;
            }

            return sortMe;
        }
    }

2 个答案:

答案 0 :(得分:3)

你的类没有返回一个新数组,它正在修改输入数组并返回对它的引用。如果您的输入是一次性的,您可以这样称呼:

int[] test = myTest.BubbleSort(Sorting.GenerateTestArray(10, 100), false);
int[] testBack = backTest.BubbleSort(Sorting.GenerateTestArray(10, 100), true);

如果从排序类中删除返回值会更清楚。这样很明显,它正在修改第一个参数,而不是创建一个新数组。例如:

int[] test = Sorting.GenerateTestArray(10, 100);
myTest.BubbleSort(test, false);

int[] testBack = Sorting.GenerateTestArray(10, 100);
backTest.BubbleSort(testBack, true);

答案 1 :(得分:0)

但它们都是对sortMe的引用

您将sortMe传递给BubbleSort