类:把数据和操作放在一起
类描述一类事物有什么数据(字段/属性)、能做什么(方法)。
using System;
class Student
{
public string Name = string.Empty;
public int Score;
public void Print()
{
Console.WriteLine($"{Name}:{Score} 分");
}
}
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.Name = "小明";
s.Score = 92;
s.Print(); // 小明:92 分
}
}
new Student() 创建对象(实例)。public 表示这个成员对外可见;不加会默认 private,外部访问不到。
属性:给字段加一道门
直接把字段公开出去,外部可以随便赋非法值。属性可以在读写时加上规则:
class Student
{
private int score;
public int Score
{
get { return score; }
set
{
if (value < 0)
{
score = 0;
}
else if (value > 100)
{
score = 100;
}
else
{
score = value;
}
}
}
}
value 是赋值进来的值。上面这种「字段 + 简单读写」的写法可以简写成自动属性:
class Student
{
public string Name { get; set; } = string.Empty;
public int Score { get; set; }
public string Id { get; } = "unknown"; // 只能读,构造时确定
public string Nickname { get; private set; } // 外部可读,只有类内部能改
}
计算属性不存储数据,每次访问时算出来:
public bool IsPassed
{
get { return Score >= 60; }
}
构造函数:对象出生时要做的事
class Student
{
public string Name { get; }
public int Score { get; }
public Student(string name, int score)
{
Name = name;
Score = score;
}
}
class Program
{
static void Main(string[] args)
{
var s = new Student("小明", 92);
Console.WriteLine(s.Name);
}
}
构造函数的名字与类名相同,没有返回类型。一旦写了带参数的构造函数,new Student() 这种无参写法就不再可用,除非再显式写一个无参构造函数。
方法的重载与 ref / out
同名方法只要参数列表不同,就可以共存:
static int Add(int a, int b) => a + b;
static double Add(double a, double b) => a + b;
static string Add(string a, string b) => a + b;
static void Main(string[] args)
{
Console.WriteLine(Add(1, 2)); // 3
Console.WriteLine(Add(1.5, 2.5)); // 4
Console.WriteLine(Add("码", "巢")); // 码巢
}
=> 写法叫表达式主体方法,一行能写完的简单方法可以这样省掉大括号。
ref 让方法修改调用方传进来的变量,out 用来返回多个结果:
static void Double(ref int value)
{
value *= 2;
}
static bool TryDiv(int a, int b, out int result)
{
if (b == 0)
{
result = 0;
return false;
}
result = a / b;
return true;
}
static void Main(string[] args)
{
int n = 5;
Double(ref n);
Console.WriteLine(n); // 10
if (TryDiv(10, 2, out int r))
{
Console.WriteLine(r); // 5
}
}
继承与多态
子类继承父类,自动拥有父类的成员,还可以改写(override)父类标记为 virtual 的行为:
class Animal
{
public string Name { get; }
public Animal(string name)
{
Name = name;
}
public virtual string Speak()
{
return "……";
}
}
class Dog : Animal
{
public Dog(string name) : base(name) { }
public override string Speak()
{
return "汪";
}
}
class Cat : Animal
{
public Cat(string name) : base(name) { }
public override string Speak()
{
return "喵";
}
}
class Program
{
static void Main(string[] args)
{
var animals = new System.Collections.Generic.List<Animal>
{
new Dog("旺财"),
new Cat("咪咪"),
};
foreach (Animal a in animals)
{
Console.WriteLine($"{a.Name}:{a.Speak()}");
}
// 旺财:汪
// 咪咪:喵
}
}
base(name) 表示调用父类的构造函数。同一个 a.Speak() 根据对象实际类型执行不同代码,这就是多态。
sealed override 可以禁止别人继续重写;abstract 抽象类则不能直接 new,只能被子类继承。
接口:约定「必须会做什么」
接口只写要求,不写实现。类实现接口后必须提供全部约定的成员:
interface IShape
{
double Area();
string Name { get; }
}
class Circle : IShape
{
private readonly double radius;
public Circle(double r)
{
radius = r;
}
public string Name => "圆";
public double Area()
{
return Math.PI * radius * radius;
}
}
class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public string Name => "矩形";
public double Area()
{
return Width * Height;
}
}
class Program
{
static void Main(string[] args)
{
var shapes = new System.Collections.Generic.List<IShape>
{
new Circle(1),
new Rectangle { Width = 3, Height = 4 },
};
foreach (IShape shape in shapes)
{
Console.WriteLine($"{shape.Name} 面积 {shape.Area():F2}");
}
}
}
接口让调用方只依赖「能力」,不关心具体是哪个类。列表、字典这些内置类型都实现了 IEnumerable<T>,所以 foreach 对它们都通用。
静态成员
属于类本身、不需要创建对象就能用:
class MathHelper
{
public static double Pi = 3.14159;
public static int Square(int x)
{
return x * x;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MathHelper.Square(5)); // 25
Console.WriteLine(MathHelper.Pi); // 3.14159
}
}
之前一直写的 static void Main 就是这个道理:入口方法属于类,运行时不需要先 new 一个对象。
枚举:一组命名的取值
enum OrderState
{
Pending, // 0
Paid, // 1
Shipped, // 2
Done, // 3
}
class Program
{
static void Main(string[] args)
{
OrderState state = OrderState.Paid;
if (state == OrderState.Paid)
{
Console.WriteLine("已支付,准备发货");
}
Console.WriteLine((int)state); // 1
Console.WriteLine(state); // Paid
}
}
枚举比用 0、1、2 直接表示状态更安全,也更易读。
异常处理:让程序优雅地失败
try
{
Console.WriteLine("请输入一个数字:");
string input = Console.ReadLine() ?? "";
int n = int.Parse(input);
Console.WriteLine($"两倍是 {n * 2}");
}
catch (FormatException)
{
Console.WriteLine("输入的不是合法数字");
}
catch (Exception ex)
{
Console.WriteLine($"出错了:{ex.Message}");
}
finally
{
Console.WriteLine("无论成败都会执行");
}
try包住可能出错的代码。catch按异常类型分别处理,从上到下匹配,Exception放最后兜底。finally用来收尾(释放资源、保存状态等),无论是否出错都执行。
也可以主动抛异常,表达「这里不该继续」:
static int Divide(int a, int b)
{
if (b == 0)
{
throw new ArgumentException("除数不能为 0");
}
return a / b;
}
不要用异常做普通的流程控制:能提前判断的就判断,异常留给真正意外的情况。
泛型:一份代码适配多种类型
把类型做成参数,写一次就能给 int、string、自定义类都用:
class Box<T>
{
public T Value { get; set; }
public Box(T value)
{
Value = value;
}
public override string ToString()
{
return $"盒子里的值是 {Value}";
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new Box<int>(42));
Console.WriteLine(new Box<string>("码巢"));
}
}
List<T>、Dictionary<K,V> 都是泛型类。自己写工具方法时,泛型能避免为每种类型都复制一份代码。
泛型方法:
static T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) >= 0 ? a : b;
}
static void Main(string[] args)
{
Console.WriteLine(Max(3, 9)); // 9
Console.WriteLine(Max("a", "c")); // c
}
where T : IComparable<T> 是约束,表示「T 必须能比较大小」,这样方法体里才能调用 CompareTo。
异步:不阻塞界面的写法
async / await 用来表示「等待一个耗时的操作,等待期间让出执行权」:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("开始");
await Task.Delay(1000); // 等待 1 秒,不阻塞界面
Console.WriteLine("一秒后");
}
}
要点:
- 入口写成
static async Task Main(string[] args)。 - 方法里用了
await,方法本身必须标async。 - 返回
Task表示「没有返回值的异步操作」,返回Task<int>则可以return 一个整数。
在码巢里需要注意:内核是单线程模型,Task.Delay 之类的等待可以正常使用,但不要写 Thread.Sleep 或 .Wait()、.Result 这类阻塞式等待,否则界面会卡住直到超时。
学完之后
到这里,C# 的常用语法已经覆盖完整。接下来建议: