C#语言开发特点详解
1. 常量变量
- 常量:使用
const声明不可修改的值,如const double PI = 3.14159; - 变量:需显式指定类型,支持类型推断(
var),如:int count = 10; // 显式类型 var message = "Hello"; // 类型推断
2. 数据类型
- 值类型:直接存储数据(
int,double,struct) - 引用类型:存储内存地址(
string,class,array) - 特殊类型:
- 可空类型:
int? nullableInt = null; - 动态类型:
dynamic obj = new ExpandoObject();
- 可空类型:
3. 表达式
- 组成:操作数 + 运算符,如:
int result = (a + b) * c; // 算术表达式 bool flag = (x > 0) && (y < 10); // 逻辑表达式 - 特殊运算符:
- 空值合并:
name ?? "Unknown" - 条件运算符:
max = (a > b) ? a : b;
- 空值合并:
4. 循环语句
// for循环
for (int i = 0; i < 10; i++) { }
// foreach循环
foreach (var item in collection) { }
// while循环
while (condition) { }
// do-while循环
do { } while (condition);
5. 选择语句
// if-else
if (score >= 90) Grade = 'A';
else if (score >= 60) Grade = 'B';
else Grade = 'C';
// switch模式匹配(C# 8.0+)
switch (shape)
{
case Circle c: Console.WriteLine($"Radius: {c.Radius}"); break;
case Rectangle r: Console.WriteLine($"Area: {r.Width * r.Height}"); break;
}
6. 顺序语句
程序默认按代码顺序执行:
Console.Write("Step1: ");
int x = Calculate(); // 先执行
Console.WriteLine(x); // 后输出
7. 内存管理
- 自动垃圾回收(GC):自动回收未引用的堆内存
- 资源释放:
using语句管理非托管资源:using (FileStream fs = new FileStream(...)) { // 自动调用Dispose() }- 实现
IDisposable接口手动释放资源
8. 算法实现
示例:快速排序算法
public void QuickSort(int[] arr, int left, int right)
{
if (left < right)
{
int pivot = Partition(arr, left, right);
QuickSort(arr, left, pivot - 1);
QuickSort(arr, pivot + 1, right);
}
}
private int Partition(int[] arr, int left, int right)
{
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++)
{
if (arr[j] <= pivot)
{
i++;
Swap(ref arr[i], ref arr[j]);
}
}
Swap(ref arr[i + 1], ref arr[right]);
return i + 1;
}
9. GUI控件
Windows Forms 常用控件:
// 创建按钮
Button btn = new Button();
btn.Text = "Click Me";
btn.Click += (sender, e) => MessageBox.Show("Clicked!");
// 文本框
TextBox txtInput = new TextBox { Width = 200 };
// 添加到窗体
Form mainForm = new Form();
mainForm.Controls.Add(btn);
mainForm.Controls.Add(txtInput);
10. MVC模式
- 模型(Model):数据逻辑(如
Product.cs)public class Product { public int Id { get; set; } public string Name { get; set; } } - 视图(View):UI展示(Razor 视图示例)
@model IEnumerable<Product> @foreach (var p in Model) { <div>@p.Name</div> } - 控制器(Controller):请求处理
public class ProductController : Controller { public IActionResult Index() { var products = _db.Products.ToList(); return View(products); } }
C#通过强类型系统、现代语法特性和.NET生态支持,在工业级应用开发中展现出高效性和可靠性。其特点包括类型安全、自动内存管理、丰富的标准库以及对多范式编程(面向对象/函数式)的支持。

被折叠的 条评论
为什么被折叠?



