小結
本入門指南旨在幫助您用 Visual Studio 建立一個簡單的 C# 專案。無法全面介紹,建議您查詢關於 C# 和 .NET 的其他資源以深入學習。完成本教學後,您至少擁有一個可用的專案,研究 Visual C# 時可從修改這些程式碼開始。
為方便起見,我們提供了完整原始程式與專案檔,可透過本文件頂部目錄存取。
其他資源
強烈推薦下列關於 C# 和 .NET 平台的書籍,是開發人員學習新技術的有益資源:
補遺:QuickSort C# .Net 原始碼
下面是 QuickSort C# .Net 範例應用程式的完整原始碼。您可以複製、使用和分發(免版權費)。注意,原始碼以「原樣」提供且不作任何保證。
// QuickSort C# .NET Sample Application
// Copyright 2001-2002 Microsoft Corporation. All rights reserved.
// MSDN ACADEMIC ALLIANCE [https://www.msdn.microsoft.com/academic]
// Import namespaces
using System;
using System.Collections;
using System.IO;
namespace MsdnAA
{
class QuickSortApp
{
static void Main(string[] szArgs)
{
Console.WriteLine("\nQuickSort C#.NET Sample Application");
Console.WriteLine("Copyright (c)2001-2002 Microsoft Corporation. All rights reserved.\n");
Console.WriteLine("MSDN ACADEMIC ALLIANCE [https://www.msdnaa.Net/]\n");
Console.WriteLine("This example demonstrates the QuickSort algorithm by reading an input file,");
Console.WriteLine("sorting its contents, and writing them to a new file.\n");
Console.Write("Source: ");
string szSrcFile = Console.ReadLine();
Console.Write("Output: ");
string szDestFile = Console.ReadLine();
string szSrcLine;
ArrayList szContents = new ArrayList();
FileStream fsInput = new FileStream(szSrcFile, FileMode.Open, FileAccess.Read);
StreamReader srInput = new StreamReader(fsInput);
while ((szSrcLine = srInput.ReadLine()) != null)
{
szContents.Add(szSrcLine);
}
srInput.Close();
fsInput.Close();
QuickSort(szContents, 0, szContents.Count - 1);
FileStream fsOutput = new FileStream(szDestFile, FileMode.Create, FileAccess.Write);
StreamWriter srOutput = new StreamWriter(fsOutput);
for (int nIndex = 0; nIndex < szContents.Count; nIndex++)
{
srOutput.WriteLine(szContents[nIndex]);
}
srOutput.Close();
fsOutput.Close();
Console.WriteLine("\nThe sorted lines have been written to the output file.\n\n");
}
private static void QuickSort(ArrayList szArray, int nLower, int nUpper)
{
if (nLower < nUpper)
{
int nSplit = Partition(szArray, nLower, nUpper);
QuickSort(szArray, nLower, nSplit - 1);
QuickSort(szArray, nSplit + 1, nUpper);
}
}
private static int Partition(ArrayList szArray, int nLower, int nUpper)
{
int nLeft = nLower + 1;
string szPivot = (string)szArray[nLower];
int nRight = nUpper;
string szSwap;
while (nLeft <= nRight)
{
while (nLeft <= nRight && ((string)szArray[nLeft]).CompareTo(szPivot) <= 0)
nLeft = nLeft + 1;
while (nLeft <= nRight && ((string)szArray[nRight]).CompareTo(szPivot) > 0)
nRight = nRight - 1;
if (nLeft < nRight)
{
szSwap = (string)szArray[nLeft];
szArray[nLeft] = szArray[nRight];
szArray[nRight] = szSwap;
nLeft = nLeft + 1;
nRight = nRight - 1;
}
}
szSwap = (string)szArray[nLower];
szArray[nLower] = szArray[nRight];
szArray[nRight] = szSwap;
return nRight;
}
}
}