繁体   English   中英

如何修复我的策略模式 C# 程序?

[英]How can I fix my Strategy Pattern C# program?

我的程序是用户可以输入任何字符串并在冒泡排序或快速排序这两个选项之间进行选择,然后我的程序将执行排序,但用户输入有问题。

我不知道如何将用户输入调用到我的 BubbleSort 和我的 Quicksort 中。

我的代码中有红线,特别是关于 Implementaion 和 userInput。 我将如何解决它? 我是创建策略模式的新手。

这是我的错误:

/Users/xhantan/Projects/SortString/SortString/Program.cs(69,29,69,38): error CS0103: The name 'userInput' does not exist in the current context
/Users/xhantan/Projects/SortString/SortString/Program.cs(70,37,70,46): error CS0103: The name 'userInput' does not exist in the current context
/Users/xhantan/Projects/SortString/SortString/Program.cs(67,23,67,36): error CS0161: 'QuickSort.Implementaion(object)': not all code paths return a value
/Users/xhantan/Projects/SortString/SortString/Program.cs(42,30,42,39): error CS0103: The name 'userInput' does not exist in the current context
/Users/xhantan/Projects/SortString/SortString/Program.cs(39,23,39,37): error CS0161: 'BubbleSort.Implementation(object)': not all code paths return a value
/Users/xhantan/Projects/SortString/SortString/Program.cs(28,40,28,54): error CS7036: There is no argument given that corresponds to the required formal parameter 'data' of 'IStrategy.Implementation(object)'
    0 Warning(s)
    6 Error(s)

这是我的代码:

using System;

namespace SortStrategyPattern
{
    class Context
    {
        private IStrategy _strategy;

        public Context()
        { }

        public Context(IStrategy strategy)
        {
            this._strategy = strategy;
        }

        public void SetStrategy(IStrategy strategy)
        {
            this._strategy = strategy;
        }

        public void UserInput()
        {
            Console.Write("Enter a string: ");

            String userInput = Console.ReadLine();

            userInput = this._strategy.Implementation();
        }
    }

    public interface IStrategy
    {
        object Implementation(object data);
    }

    class BubbleSort : IStrategy
    {
        public object Implementation(object data)
        {
            char temp;
            char[] charStr = userInput.ToCharArray();
            for (int x = 1; x < charStr.Length; x++)
            {
                for (int y = 0; y < charStr.Length - 1; y++)
                {
                    if (charStr[y] > charStr[y + 1])
                    {
                        temp = charStr[y];
                        charStr[y] = charStr[y + 1];
                        charStr[y + 1] = temp;
                    }
                }
            }


            Console.Write("Bubble Sort: ");
            foreach (char input in charStr)
            {
                Console.Write(input + ", ");
            }
        }
    }

    class QuickSort : IStrategy
    {
        public object Implementaion(object data)
        {
            var charArray = userInput.ToCharArray();
            quicksort(charArray, 0, userInput.Length);

            Console.Write("Quick Sort: ");
            foreach (char s in charArray)
            {
                Console.Write(s + ", ");
            }
        }

        static void quicksort(char[] userInput, int start, int end)
        {
            if (start < end)
            {
                int pivotIndex = partition(userInput, start, end);
                quicksort(userInput, start, pivotIndex);
                quicksort(userInput, pivotIndex + 1, end);
            }
        }

        static void swap(char[] userInput, int i, int j)
        {
            char temp = userInput[i];
            userInput[i] = userInput[j];
            userInput[j] = temp;
        }

        static int partition(char[] userInput, int start, int end)
        {
            int pivotIndex = userInput[start];
            int swapIndex = start;
            for (int i = start + 1; i < end; i++)
            {
                if (userInput[i] < pivotIndex)
                {
                    swapIndex++;
                    swap(userInput, i, swapIndex);
                }
            }
            swap(userInput, start, swapIndex);
            return swapIndex;
        }

        public object Implementation(object data)
        {
            throw new NotImplementedException();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            char response;

            do
            {
                Console.WriteLine();
                Console.WriteLine("Choose between the two sorting strategies:");
                Console.WriteLine("\ta) - Bubble Sort");
                Console.WriteLine("\tb) - Quick Sort");
                Console.WriteLine();
                Console.Write("Your option: ");

                {
                    response = char.Parse(Console.ReadLine());
                }

                Console.WriteLine();

                switch (response.ToString().ToLower())
                {
                    case "a":

                        new BubbleSort();
                        break;


                    case "b":

                        new QuickSort();
                        break;

                    default:
                        Console.WriteLine("Invalid answer. Please enter a valid option.");
                        response = '\0';
                        break;
                }

            } while (response == '\0');
        }
    }
}

你快到了。 但是,让我们稍微改进一下:

界面

public interface ISort
{
   T[] Sort<T>(T[] data) where T : IComparable;
}

冒泡排序

public class BubbleSort : ISort
{
   public T[] Sort<T>(T[] data) where T : IComparable
   {
      var result = data.ToArray();
      for (var x = 1; x < result.Length; x++)
      {
         for (var y = 0; y < result.Length - 1; y++)
         {
            if (result[y].CompareTo(result[y + 1]) <= 0) continue;
            var temp = result[y];
            result[y] = result[y + 1];
            result[y + 1] = temp;
         }
      }

      return result;
   }
}

快速排序

public class QuickSort : ISort
{
   public T[] Sort<T>(T[] data) where T : IComparable
   {
      var result = data.ToArray();
      InternalQuickSort(result, 0, result.Length);
      return result;

   }

   private static void InternalQuickSort<T>(T[] data, int start, int end) where T : IComparable
   {
      if (start >= end) return;
      var pivotIndex = Partition(data, start, end);
      InternalQuickSort(data, start, pivotIndex);
      InternalQuickSort(data, pivotIndex + 1, end);
   }

   private static void Swap<T>(T[] data, int i, int j) where T : IComparable
   {
      T temp = data[i];
      data[i] = data[j];
      data[j] = temp;
   }

   private static int Partition<T>(T[] data, int start, int end) where T : IComparable
   {
      var pivotIndex = data[start];
      var swapIndex = start;
      for (var i = start + 1; i < end; i++)
      {
         if (data[i].CompareTo(pivotIndex) >= 0) continue;
         swapIndex++;
         Swap(data, i, swapIndex);
      }

      Swap(data, start, swapIndex);
      return swapIndex;
   }
}

用法

private static ISort GetSorter(char option)
   => char.ToLower(option) switch
   {
      'a' => new BubbleSort(),
      'b' => new QuickSort(),
      _ => null
   };

static void Main(string[] args)
{
   char response;

   do
   {
      Console.WriteLine();
      Console.WriteLine("Choose between the two sorting strategies:");
      Console.WriteLine("\ta) - Bubble Sort");
      Console.WriteLine("\tb) - Quick Sort");
      Console.WriteLine("\tx) - To Quit");
      Console.WriteLine();
      Console.Write("Your option: ");

      if (!char.TryParse(Console.ReadLine(), out response))
         continue;

      if (response == 'x')
         break;

      var sorter = GetSorter(response);

      if (sorter == null)
         continue;

      Console.Write("Type something to sort: ");

      var data = Console.ReadLine();

      Console.WriteLine();

      var result = sorter.Sort(data.ToCharArray());

      Console.WriteLine(string.Join(", ", result));

   } while (response != 'x');
}

Output

Choose between the two sorting strategies:
        a) - Bubble Sort
        b) - Quick Sort
        x) - To Quit

Your option: a
Type something to sort: qwertyuiop

e, i, o, p, q, r, t, u, w, y

Choose between the two sorting strategies:
        a) - Bubble Sort
        b) - Quick Sort
        x) - To Quit

Your option: b
Type something to sort: qwertyuiop

e, i, o, p, q, r, t, u, w, y

Choose between the two sorting strategies:
        a) - Bubble Sort
        b) - Quick Sort
        x) - To Quit

Your option: x

其他资源

Generics(C#编程指南)

Generics 将类型参数的概念引入 .NET,这使得设计类和方法成为可能,这些类和方法将一种或多种类型的规范推迟到 class 或方法被客户端代码声明和实例化。 例如,通过使用泛型类型参数 T,您可以编写其他客户端代码可以使用的单个 class,而不会产生运行时强制转换或装箱操作的成本或风险

IComparable 接口

定义值类型或 class 实现的通用类型特定比较方法,以对其实例进行排序或排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM