Stories

Detail Return Return

深入理解 C# 編程:枚舉、文件處理、異常處理和數字相加 - Stories Detail

C# 枚舉

枚舉是一個特殊的“類”,表示一組常量(不可更改/只讀變量)。

要創建枚舉,請使用 enum 關鍵字(而不是 classinterface),並用逗號分隔枚舉項:

enum Level 
{
  Low,
  Medium,
  High
}

您可以使用點語法訪問枚舉項:

Level myVar = Level.Medium;
Console.WriteLine(myVar);

Enum 是 "enumerations" 的縮寫,意思是“特定列舉”。

在類內部定義枚舉也是可行的:

class Program
{
  enum Level
  {
    Low,
    Medium,
    High
  }
  static void Main(string[] args)
  {
    Level myVar = Level.Medium;
    Console.WriteLine(myVar);
  }
}

輸出將為:

Medium

枚舉值

默認情況下,枚舉的第一項的值為 0。第二項的值為 1,依此類推。

要從項中獲取整數值,必須顯式將項轉換為 int

enum Months
{
  January,    // 0
  February,   // 1
  March,      // 2
  April,      // 3
  May,        // 4
  June,       // 5
  July        // 6
}

static void Main(string[] args)
{
  int myNum = (int) Months.April;
  Console.WriteLine(myNum);
}

輸出將為:

3

您還可以分配自己的枚舉值,接下來的項將相應地更新它們的數字:

enum Months
{
  January,    // 0
  February,   // 1
  March=6,    // 6
  April,      // 7
  May,        // 8
  June,       // 9
  July        // 10
}

static void Main(string[] args)
{
  int myNum = (int) Months.April;
  Console.WriteLine(myNum);
}

輸出將為:

7

在 Switch 語句中使用枚舉

枚舉通常在 switch 語句中用於檢查相應的值:

enum Level 
{
  Low,
  Medium,
  High
}

static void Main(string[] args) 
{
  Level myVar = Level.Medium;
  switch(myVar) 
  {
    case Level.Low:
      Console.WriteLine("低級別");
      break;
    case Level.Medium:
       Console.WriteLine("中級別");
      break;
    case Level.High:
      Console.WriteLine("高級別");
      break;
  }
}

輸出將為:

中級別

何時以及為什麼使用枚舉?

在有些情況下,當您知道值不會更改時,例如月份、日期、顏色、撲克牌等時,請使用枚舉。

C# 文件

處理文件

System.IO 命名空間中的 File 類允許我們處理文件:

using System.IO;  // 包含 System.IO 命名空間

File.SomeFileMethod();  // 使用帶有方法的 File 類

File 類具有許多有用的方法,用於創建文件和獲取有關文件的信息。例如:

方法 描述
AppendText() 在現有文件的末尾追加文本
Copy() 複製文件
Create() 創建或覆蓋文件
Delete() 刪除文件
Exists() 測試文件是否存在
ReadAllText() 讀取文件的內容
Replace() 用另一個文件的內容替換文件的內容
WriteAllText() 創建新文件並將內容寫入其中。如果文件已存在,將覆蓋它。

有關 File 方法的完整列表,請參閲 Microsoft .Net File Class 參考文檔.

寫入文件並讀取它

在以下示例中,我們使用 WriteAllText() 方法創建一個名為 "filename.txt" 的文件,並向其中寫入一些內容。然後,我們使用 ReadAllText() 方法讀取文件的內容:

using System.IO;  // 包含 System.IO 命名空間

string writeText = "Hello World!";  // 創建一個文本字符串
File.WriteAllText("filename.txt", writeText);  // 創建文件並將 writeText 的內容寫入其中

string readText = File.ReadAllText("filename.txt");  // 讀取文件的內容
Console.WriteLine(readText);  // 輸出內容

輸出將為:

Hello World!

C# 異常

在執行 C# 代碼時,可能會發生不同類型的錯誤:由程序員製造的編碼錯誤,由於錯誤的輸入或其他不可預見的事物而導致的錯誤。

當發生錯誤時,C# 通常會停止執行並生成錯誤消息。這種情況的技術術語是:C# 會引發異常(拋出錯誤)。

C# try 和 catch

try 語句允許您定義一塊在執行過程中測試錯誤的代碼塊。

catch 語句允許您定義一塊在 try 塊中發生錯誤時執行的代碼塊。

trycatch 關鍵字是成對出現的:

try 
{
  // 試圖執行的代碼塊
}
catch (Exception e)
{
  // 處理錯誤的代碼塊
}

考慮以下示例,我們在其中創建一個包含三個整數的數組:

這將生成一個錯誤,因為 myNumbers[10] 不存在。

int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]); // error!

錯誤消息將類似於:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

如果發生錯誤,我們可以使用 try...catch 來捕獲錯誤並執行一些代碼來處理它。

在以下示例中,我們在 catch 塊中使用變量(e)以及內置的 Message 屬性,該屬性輸出描述異常的消息:

try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine(e.Message);
}

輸出將為:

Index was outside the bounds of the array.

您還可以輸出自己的錯誤消息:

try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine("Something went wrong.");
}

輸出將為:

Something went wrong.

finally 塊

finally 語句允許您在 try...catch 之後執行代碼,無論結果如何:

try
{
  int[] myNumbers = {1, 2, 3};
  Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
  Console.WriteLine("Something went wrong.");
}
finally
{
  Console.WriteLine("The 'try catch' is finished.");
}

輸出將為:

Something went wrong.
The 'try catch' is finished.

throw 關鍵字

throw 語句允許您創建自定義錯誤。

throw 語句與異常類一起使用。在 C# 中有許多異常類可用:ArithmeticExceptionFileNotFoundExceptionIndexOutOfRangeExceptionTimeOutException 等:

static void checkAge(int age)
{
  if (age < 18)
  {
    throw new ArithmeticException("Access denied - You must be at least 18 years old.");
  }
  else
  {
    Console.WriteLine("Access granted - You are old enough!");
  }
}

static void Main(string[] args)
{
  checkAge(15);
}

程序中顯示的錯誤消息將為:

System.ArithmeticException: 'Access denied - You must be at least 18 years old.'

如果 age 為 20,則不會引發異常:

checkAge(20);

輸出將為:

Access granted - You are old enough!

C# 如何相加兩個數字

學習如何在 C# 中相加兩個數字:

// 示例
int x = 5;
int y = 6;
int sum = x + y;
Console.WriteLine(sum); // 打印 x + y 的和

最後

為了方便其他設備和平台的小夥伴觀看往期文章:

微信公眾號搜索:Let us Coding,關注後即可獲取最新文章推送

看完如果覺得有幫助,歡迎 點贊、收藏、關注

user avatar leixue Avatar u_15988698 Avatar aitaokedemugua Avatar teamcode Avatar u_15700751 Avatar blbl-blog Avatar eolink Avatar duiniwukenaihe_60e4196de52b7 Avatar yian Avatar wnhyang Avatar cbuc Avatar renzhendezicai Avatar
Favorites 58 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.