跳過到頁腳內容
Iron Academy Logo
學習 C#
學習 C#

其他分類

理解 C# 變量和數據類型

Tim Corey
28m 27s

在C#程式設計中,變數是存儲資料值的基礎元素。 了解如何有效地定義和使用變數對於撰寫高效和可維護的程式碼至關重要。 變數可以是不同的型別,包括基本資料型別、常數和動態型別變數,每種型別都服務於特定的用途。 此外,類型轉換、dynamic和var關鍵字為C#程式設計增添了靈活性和穩健性。

Tim Corey 的影片《C#中的Dynamic與Var》全面概述了這些概念。在本文中,我們將探討Tim所涵蓋的幾個主題,包括:

  1. Dynamic與Var的區別
    • 基本資料型別
    • 變數與常數
  2. 動態自動型別轉換
  3. Dynamic在開發中的缺點
  4. Dynamic的使用理由和時機
  5. Var的使用理由和時機

通過Tim Corey的講解,您將更深入地了解如何在C#中有效地管理和利用變數。

Dynamic與Var的區別

在C#中,var用於隱式型別本地變數,這些變數的型別在編譯期間確定,確保類型安全和IntelliSense支援。 相比之下,dynamic允許變數繞過編譯期類型檢查,型別在運行期間決定,提供了更高的靈活性,但也伴隨著運行時錯誤和性能下降的風險。

Tim Corey 解釋說,dynamic通過運行時型別決議提供靈活性,這可能導致運行時錯誤和性能問題。

基本資料型別

Tim在Visual Studio中開始他的演示,介紹C#中的基本資料型別。 他創建了一個名為dynamic的對象,該對象可以隨時分配新值,其型別可以在運行時動態更改。以下代碼展示了這一點:

// Declaration of a dynamic variable that can change types at runtime
dynamic testDynamic;
// Declaration of a dynamic variable that can change types at runtime
dynamic testDynamic;

C# 提供了幾種基本資料型別來處理各種數據。 整數型別包括32位帶符號整數的byte。 對於浮點數,C#提供了32位單精度值的decimal,適合用於金融計算。 bool類型用於顯示真或假值。 此外,string資料型別表示字符序列,允許存儲和操作文本。

這些資料型別是C#程式設計的基礎,能夠有效地存儲和操作資料,正如Tim在後續示例中所示。 多個變數可以在一行中宣告並分配整數類型int,如果未明確分配初始值,每個資料型別都有一個默認值。 常數變數保持固定值,為程式碼提供一致性。 此外,實例變數和靜態變數也可以使用這些資料型別宣告,確保程式結構的穩健性和靈活性。

變數和常數

在1:21,Tim Corey嘗試創建一個名為var需要初始分配來推斷其型別:

// This will result in a compile-time error due to lack of type inference
// var testVar;
// This will result in a compile-time error due to lack of type inference
// var testVar;

這會導致testVar下方出現紅色波浪線,表示錯誤。 在1:55,Tim說明var需要在宣告時分配型別。 例如:

// var assignment with type inference from the initial value
var testVar = 2; // testVar is inferred to be of type int
// var assignment with type inference from the initial value
var testVar = 2; // testVar is inferred to be of type int

在2:44,Tim演示如果他後來嘗試為int

// Attempting to change the type from int to double causes an error
// testVar = 1.1; // Error: Cannot implicitly convert type 'double' to 'int'
// Attempting to change the type from int to double causes an error
// testVar = 1.1; // Error: Cannot implicitly convert type 'double' to 'int'

在3:17,Tim強調var的類型在初始分配時設定,之後不能更改。 如果testVar最初被分配一個雙精度值,它將被推斷為雙精度:

// Another example with dynamic typing
var testVar = 2.1; // Now testVar is a double
// Another example with dynamic typing
var testVar = 2.1; // Now testVar is a double

儘管Tim沒有討論常數變數,但它們在C#程式中同樣重要。 在C#中,常數使用const關鍵字聲明,後面跟著常數變數的資料型別和識別符,如:

// Declaring a constant variable
const int MaxValue = 100;
// Declaring a constant variable
const int MaxValue = 100;

常數在聲明時必須賦值,在程式執行期間不能更改,為程式邏輯提供不可變值。

動態自動型別轉換

Tim強調object的行為實現靈活的型別處理,但具有更多的功能。 在3:53,Tim展示dynamic如何在運行時間無縫地在不同類型之間轉換,展示其在計算涉及整數和雙精度浮點數時無需顯式轉型的能力,如他的代碼示例所示:

// Demonstrating dynamic type conversion at runtime
dynamic testDynamic = 1;
testDynamic = testDynamic + 2.1;
Console.WriteLine(testDynamic); // Outputs 3.1 as it converts the integer to a double
// Demonstrating dynamic type conversion at runtime
dynamic testDynamic = 1;
testDynamic = testDynamic + 2.1;
Console.WriteLine(testDynamic); // Outputs 3.1 as it converts the integer to a double

在這裡,Tim(4:39)演示testDynamic最初持有整數值,但在加入2.1時輕易地將其轉為雙精度,結果輸出是3.1。

儘管具有靈活性,Tim提醒不要過度使用dynamic,因為頻繁的型別轉換會導致性能開銷。 在5:55,他強調dynamic應在C#開發中謹慎使用,以避免不必要的處理器負擔以及失去編譯時型別檢查和IntelliSense支援,這對於維護穩健和無錯誤的程式碼庫至關重要。

Dynamic在開發中的缺點

Tim Corey展示dynamic如何導致運行時錯誤和應用程式中的意外行為。 他首先演示如何宣告動態變數並分配初始空字串以避免立即出錯。 然後他嘗試調用不存在的方法dynamic的一個主要缺點:缺乏編譯時檢查。

// Demonstrating lack of compile-time checks with dynamic
dynamic testDynamic = "";
// testDynamic.sayHi(); // Runtime error: method does not exist
// Demonstrating lack of compile-time checks with dynamic
dynamic testDynamic = "";
// testDynamic.sayHi(); // Runtime error: method does not exist

此外,在8:38,Tim展示動態變數如何在運行時改變型別,這可能導致意外行為。 他將Person對象賦給動態變數,然後重新賦值為字串,展示這種靈活性如何導致邏輯錯誤並使調試困難。

// Demonstrating the potential errors with dynamic type reassignment
dynamic testDynamic = new Person();
testDynamic = "Hi";
Console.WriteLine(testDynamic); // Works fine, but not ideal for type safety
// Demonstrating the potential errors with dynamic type reassignment
dynamic testDynamic = new Person();
testDynamic = "Hi";
Console.WriteLine(testDynamic); // Works fine, but not ideal for type safety

Tim還解釋動態變數缺乏IntelliSense支援,這可能由於拼寫錯誤或不正確的方法名稱而導致運行時錯誤。 例如,在14:05,他呼叫一個不存在的屬性名稱Person對象上期望的方法或屬性不存在於字串上。

// Demonstrating a runtime error due to missing property
// testDynamic.Email = "Test@test.com"; // property not found until runtime
// Demonstrating a runtime error due to missing property
// testDynamic.Email = "Test@test.com"; // property not found until runtime

使用Var關鍵字的優勢

相比之下,var是強類型的,並提供編譯時型別檢查和IntelliSense支援。 這確保任何與型別相關的問題在開發過程中被捕獲,從而使代碼更可靠並更易於維護。 Tim Corey通過創建Person對象來演示這一點:

// Using var for strongly-typed assignments
var testVar = new Person();
testVar.FirstName = "Sue";
testVar.LastName = "Storm";

// The use of IntelliSense assists in reducing runtime errors
Console.WriteLine(testVar.SayHello()); // Ideally a method in Person class
// Using var for strongly-typed assignments
var testVar = new Person();
testVar.FirstName = "Sue";
testVar.LastName = "Storm";

// The use of IntelliSense assists in reducing runtime errors
Console.WriteLine(testVar.SayHello()); // Ideally a method in Person class

嘗試調用不存在的方法或將var變數重新分配為不同型別將在編譯時捕獲,防止潛在的運行時錯誤。

// Attempting to change type results in compile-time errors with var
// testVar = "Hi"; // Compile-time error
// Attempting to change type results in compile-time errors with var
// testVar = "Hi"; // Compile-time error

方法返回型態

在15:05,Tim演示您可以從方法中返回var。 例如:

// Method returning a dynamic type
public dynamic GetMessage() {
    return "This is a test";
}
// Method returning a dynamic type
public dynamic GetMessage() {
    return "This is a test";
}

嘗試返回var會導致編譯時錯誤,因為方法簽名必須指定具體的返回型態。

使用Dynamic的理由和時機

Tim詳細闡述dynamic成為必要的具體場景。 他解釋到,C#本質上是一種強類型語言,意味著每個變數都被分配了一個明確的型別,這在其生命周期內保持一致。 這與JavaScript等語言形成對比,後者中變數可以動態改變型別。

在18:14,Tim展示雖然C#被設計為強類型變數,但在某些情況下,特別是與外部系統或諸如Python、Ruby或COM對象之類的語言交互時,動態類型可能有用。 他使用整合Python API的示例來突顯dynamic的實際需求。 在這些情況下,擁有一個能夠適應外部來源各種資料型別的靈活型別系統簡化了交互。

在18:44,Tim Corey強調dynamic對於跨語言交互有用,但由於失去編譯時錯誤檢查和IntelliSense支援,通常不建議用於純C#代碼。 他警告說,dynamic的靈活性以性能和類型安全為代價,是C#常規編程中不那麼理想的選擇,應優先使用強類型變數。

使用Var關鍵字的理由和時機

然後Tim討論var關鍵字在C#中的用法和哲學。 他指出,對於使用var有兩個主要陣營:那些喜好只使用它的和那些偏好顯式型別聲明的。

在19:43,Tim解釋讚成var的人認為這會鼓勵更好的命名慣例,使代碼具有自我說明性。 他們認為變數名稱應該足夠描述性,以在不需要顯式聲明的情況下傳達型別。

在另一方面,避免顯式型別聲明的人認為在代碼中直接看到實際型別可以使局部變數的型別一目了然,而不需要將滑鼠懸停在變數上以查看其類型。 例如:

// Explicit type declaration provides clarity
string firstName = "Tim";
// Explicit type declaration provides clarity
string firstName = "Tim";

一些人偏好這種方式,因為它消除了對變數類型的任何模糊性。

在21:15,Tim分享了他的一個平衡方式,表示他通常使用顯式類型來處理常見資料型別,比如decimal的混淆。 例如:

// Explicit type ensures there's no ambiguity between float types
double myMoney = 1.1; // This is a double
decimal myMoney = 1.1M; // This is a decimal
// Explicit type ensures there's no ambiguity between float types
double myMoney = 1.1; // This is a double
decimal myMoney = 1.1M; // This is a decimal

Tim強調明確聲明類型可以確保使用正確的類型,特別是當類似類型之間可能混淆時。

然而,Tim也承認List<List<Person>>可能顯得冗長:

// Declaring a complex type using var
var rounds = new List<List<Person>>();
// Declaring a complex type using var
var rounds = new List<List<Person>>();

他還在foreach循環中演示了它的實用性(23:55):

// Utilizing var in loop for cleaner code
foreach (var round in rounds) {
    // Do something with each round
}
// Utilizing var in loop for cleaner code
foreach (var round in rounds) {
    // Do something with each round
}

Tim最後總結說,雖然var可以減少冗長,但這很重要確保變數名稱清晰且具描述性以保持可讀性並避免混淆。

通過將var與顯式類型的使用相結合,開發者可以根據上下文適當利用兩種方法的優勢,撰寫清晰、可維護且高效的程式碼。

Var作為匿名對象

Tim討論var用於類型不明確或使用匿名型別的情況。他通過即時創建一個沒有預定型別的匿名對象來演示這一點。 這是他使用的程式碼:

// Creating an anonymous object with var
var myItem = new { FirstName = "Tim", Email = "test@test.com" };
// Creating an anonymous object with var
var myItem = new { FirstName = "Tim", Email = "test@test.com" };

在25:30,Tim解釋由於這個對象是匿名的,沒有具體的型名,所以宣告變數的唯一方法是使用var。 這種方法允許創建和使用對象而不需定義正式的類。

為了展示這在實際中的運作情況,Tim寫道(25:52):

// Outputting properties of an anonymous object
Console.WriteLine($"Hello {myItem.FirstName}: your email is {myItem.Email}");
// Outputting properties of an anonymous object
Console.WriteLine($"Hello {myItem.FirstName}: your email is {myItem.Email}");

當他在26:25運行程式碼時,輸出是:

這表明var可以處理匿名對象的屬性,儘管該對象是匿名的,Visual Studio仍能為這些屬性提供IntelliSense支援。

在26:54,Tim澄清他更喜歡對於像string、整數和類實例等簡單和常見類型使用顯式類型,因為這讓程式碼更清晰。 然而,他在類型長、複雜或未明確知道時使用var,例如匿名類型或複雜的型別宣告。

結論

這就是您所理解的——C#變數和資料型別的清晰理解以及dynamic關鍵字的戰略使用。 通過遵循Tim Corey的平衡方法,您可以在代碼中確保類型安全和清晰,與此同時在特定場景如與外部系統交互時利用var關鍵字的靈活性。

要獲得更詳細的見解,請一定要觀看Tim Corey的影片《C#中的Dynamic與Var》並查看他的YouTube頻道以了解更多C#學習主題。

Hero Worlddot related to 理解 C# 變量和數據類型
Hero Affiliate related to 理解 C# 變量和數據類型

通過分享您所愛的東西賺得更多

您是否在為使用.NET、C#、Java、Python或Node.js的開發者創建內容?將您的專業知識轉化為額外收入!

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我