數據類型
C#是一種強類型語言,變量必須聲明類型。基本數據類型包括整型(int、long)、浮點型(float、double)、布爾型(bool)、字符型(char)和字符串型(string)。引用類型包括類、接口、數組等。
int age = 25;
double price = 19.99;
bool isActive = true;
char grade = 'A';
string name = "John";
變量與常量
變量用于存儲數據,使用前需聲明類型。常量使用const
關鍵字定義,初始化后不可更改。
int counter = 10;
const double PI = 3.14159;
運算符
C#支持算術運算符(+、-、*、/)、比較運算符(==、!=、>、<)、邏輯運算符(&&、||、!)和賦值運算符(=、+=、-=)。
int sum = 10 + 5;
bool isEqual = (sum == 15);
bool result = (true && false);
控制流語句
條件語句包括if-else
和switch
,循環語句包括for
、while
和do-while
。
if (age >= 18)
{Console.WriteLine("Adult");
}for (int i = 0; i < 5; i++)
{Console.WriteLine(i);
}while (counter > 0)
{counter--;
}
方法
方法是包含一系列語句的代碼塊,通過return
返回值(無返回值用void
)。參數可傳遞值或引用(ref
、out
)。
int Add(int a, int b)
{return a + b;
}void PrintMessage(string message)
{Console.WriteLine(message);
}
類和對象
類是面向對象的基礎,包含字段、屬性、方法和構造函數。對象是類的實例。
class Person
{public string Name { get; set; }public int Age { get; set; }public Person(string name, int age) {Name = name;Age = age;}public void Introduce() {Console.WriteLine($"Name: {Name}, Age: {Age}");}
}Person person = new Person("Alice", 30);
person.Introduce();
異常處理
使用try-catch-finally
塊處理運行時錯誤,確保程序健壯性。
try
{int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{Console.WriteLine("Cannot divide by zero.");
}
finally
{Console.WriteLine("Cleanup code here.");
}
集合類型
常見集合包括數組(Array)、列表(List)、字典(Dictionary)等,用于管理數據組。
int[] numbers = { 1, 2, 3 };
List<string> names = new List<string> { "Alice", "Bob" };
Dictionary<int, string> employees = new Dictionary<int, string>();
命名空間
命名空間用于組織代碼,避免命名沖突。通過using
指令引入。
using System;
namespace MyApp
{class Program { ... }
}