身為初級開發人員,我一直害怕學習主要使用 OOP 範式的「舊」程式語言。然而,今天我決定忍住,至少試試看。它並不像我想像的那麼糟糕,它與 Javascript 有相似之處。讓我們先來了解一下基礎知識。
本部落格假定您了解 javascript
與動態類型語言 javascript 不同,C# 是靜態類型語言:變數的資料類型在編譯時就已知,這意味著程式設計師必須在變數使用時指定變數的資料類型。宣言。
int: number (32bit) decimal: number (128bit) string: string bool: Boolean list[]: Array dictionary{}: Object
-------------- Declaration ---------------- int myInt = 2147483647; decimal myDecimal = 0.751m; // The m indicates it is a decimal string myString = "Hello World"; // Notice the double-quotes bool myBool = true;
注意:如果使用方法1和2,則無法添加或延長長度
聲明和分配List方法1
string[] myGroceryArray = new string[2]; // 2 is the length myGroceryArray[0] = "Guacamole";
聲明與賦值List方法2
string[] mySecondGroceryArray = { "Apples", "Eggs" };
聲明與賦值List方法3
ListmyGroceryList = new List () { "Milk", "Cheese" }; Console.WriteLine(myGroceryList[0]); //"Milk" myGroceryList.Add("Oranges"); //Push new item to array
聲明與分配多維列表
「,」的數量將決定尺寸
string[,] myTwoDimensionalArray = new string[,] { { "Apples", "Eggs" }, { "Milk", "Cheese" } };
專門用於枚舉或循環的陣列。
你可能會問,「跟清單有什麼差別?」。答案是:
IEnumerable 和 List 之間的一個重要區別(除了一個是接口,另一個是具體類別)是 IEnumerable 是唯讀的,而 List 不是。
ListmyGroceryList = new List () { "Milk", "Cheese" }; IEnumerable myGroceryIEnumerable = myGroceryList;
DictionarymyGroceryDictionary = new Dictionary (){ {"Dairy", new string[]{"Cheese", "Milk", "Eggs"}} }; Console.WriteLine(myGroceryDictionary["Dairy"][2]);
C# 中的運算子的行為與 javascript 非常相似,所以我不會在這裡描述它
//Logic gate //There's no === in C# myInt == mySecondInt myInt != mySecondInt myInt >= mySecondInt myInt > mySecondInt myInt循環
?使用 foreach 比常規 for 迴圈
快得多int[] intArr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int totalValue = 0; for (int i = 0; i方法
C# 首先是一種面向 OOP 的語言。
namespace HelloWorld { internal class Program { static void Main() { int[] numArr = [1, 2, 3, 4, 5]; int totalSum = GetSum(numArr); } static private int GetSum(int[] numArr) { int totalValue = 0; foreach (var item in numArr) { totalValue = item; } return totalValue; } } }聲明命名空間和模型
命名空間用於組織目的,通常用於組織類別
namespace HelloWorld.Models { public class Computer { public string Motherboard { get; set; } = ""; public int CPUCores { get; set; } public bool HasWIfi { get; set; } public bool HasLTE { get; set; } public DateTime ReleaseDate { get; set; } public decimal Price { get; set; } public string VideoCard { get; set; } = ""; }; }從 C# 10 開始,我們也可以這樣宣告命名空間
namespace SampleNamespace; class AnotherSampleClass { public void AnotherSampleMethod() { System.Console.WriteLine( "SampleMethod inside SampleNamespace"); } }導入命名空間
using HelloWorld.Models;
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3