[英]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 將類型參數的概念引入 .NET,這使得設計類和方法成為可能,這些類和方法將一種或多種類型的規范推遲到 class 或方法被客戶端代碼聲明和實例化。 例如,通過使用泛型類型參數 T,您可以編寫其他客戶端代碼可以使用的單個 class,而不會產生運行時強制轉換或裝箱操作的成本或風險
定義值類型或 class 實現的通用類型特定比較方法,以對其實例進行排序或排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.