C#基础语法

C# 基础语法概述

C# 是一种面向对象的编程语言,语法清晰且类型安全。以下是核心语法要点:


数据类型与变量声明

C# 是强类型语言,变量需明确指定类型或使用 var 推断:

int num = 10;           // 整型
double pi = 3.14;       // 浮点型
string text = "Hello";  // 字符串
bool flag = true;       // 布尔型
var anonymous = 5;      // 自动推断为 int


控制结构

条件语句

if (condition) { /* 代码块 */ }
else if (condition) { /* 代码块 */ }
else { /* 代码块 */ }

switch (value) {
    case 1: break;
    default: break;
}

循环语句

for (int i = 0; i < 10; i++) { /* 代码块 */ }
while (condition) { /* 代码块 */ }
do { /* 代码块 */ } while (condition);
foreach (var item in collection) { /* 代码块 */ }


方法与参数

方法定义需指定返回类型(void 表示无返回值):

int Add(int a, int b) {
    return a + b;
}

void Print(string message) {
    Console.WriteLine(message);
}

参数传递

  • 值参数(默认):传递副本。
  • 引用参数(ref/out):直接操作原变量。
void Modify(ref int x) { x *= 2; }
void Initialize(out int y) { y = 42; }


类与对象

类是面向对象的基础,包含字段、属性和方法:

class Person {
    private string _name;  // 字段

    public string Name {   // 属性
        get { return _name; }
        set { _name = value; }
    }

    public void Greet() {  // 方法
        Console.WriteLine($"Hello, {_name}");
    }
}

// 使用
Person p = new Person();
p.Name = "Alice";
p.Greet();


异常处理

通过 try-catch-finally 捕获异常:

try {
    int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex) {
    Console.WriteLine("除零错误");
}
catch (Exception ex) {
    Console.WriteLine("其他错误");
}
finally {
    Console.WriteLine("清理资源");
}


集合与泛型

常用集合类型位于 System.Collections.Generic 命名空间:

List<int> numbers = new List<int> { 1, 2, 3 };
Dictionary<string, int> ages = new Dictionary<string, int> {
    { "Alice", 25 },
    { "Bob", 30 }
};


委托与事件

委托用于封装方法引用,事件基于委托实现:

public delegate void Notify();  // 委托定义

class Publisher {
    public event Notify OnEvent;  // 事件声明

    public void RaiseEvent() {
        OnEvent?.Invoke();  // 触发事件
    }
}


LINQ 查询

语言集成查询(LINQ)简化数据操作:

var filtered = from num in numbers 
               where num > 5 
               select num;

// 等效方法语法
var result = numbers.Where(n => n > 5).ToList();


以上是 C# 的基础语法核心内容,掌握后可进一步学习异步编程(async/await)、特性(Attributes)等高级特性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值