C# 类(Class)

字段、属性、构造函数、静态成员、以及对象初始化器。

Beginner
Key Points类是引用类型;构造函数保证对象一创建就是合法的。

定义一个类

C#
class Product
{
    // 字段
    private int _stock;

    // 属性
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public decimal Price { get; set; }

    // 计算属性
    public bool InStock => _stock > 0;

    // 构造函数
    public Product(int id, string name, decimal price)
    {
        Id = id;
        Name = name;
        Price = price;
    }

    // 无参构造
    public Product() : this(0, "未命名", 0m) { }

    // 方法
    public void Restock(int qty) => _stock += qty;

    public override string ToString() => $"[{Id}] {Name} ¥{Price}";
}

var p = new Product(1, "键盘", 199m);
p.Restock(10);
Console.WriteLine(p);
Console.WriteLine(p.InStock);
Output
[1] 键盘 ¥199
True

对象初始化器

C#
class Config
{
    public string Host { get; set; } = "localhost";
    public int Port { get; set; } = 80;
    public List<string> Tags { get; } = new();
}

var c = new Config
{
    Host = "example.com",
    Port = 8080,
    Tags = { "web", "prod" }        // 集合初始化器
};

Console.WriteLine($"{c.Host}:{c.Port} {string.Join(",", c.Tags)}");
Output
example.com:8080 web,prod

Tags = { ... } calls Add on the existing collection; Tags = new List<string>{...} replaces it. Since Tags is get-only, only the former compiles.

静态成员

C#
class Counter
{
    public static int Total { get; private set; }
    public int Local { get; private set; }

    public static Counter Create()
    {
        Total++;
        return new Counter { Local = 1 };
    }

    static Counter() { Total = 0; }     // 静态构造,只执行一次
}

Counter.Create();
Counter.Create();
Console.WriteLine(Counter.Total);
Output
2

继承与密封

C#
class Animal
{
    public string Name { get; set; } = "";
    public virtual string Speak() => "...";
}

class Dog : Animal
{
    public override string Speak() => "汪汪";
}

// sealed:不能再被继承
sealed class Puppy : Dog
{
    public override string Speak() => "嗷嗷";
}

Animal[] animals = { new Animal { Name = "?" }, new Dog { Name = "旺财" }, new Puppy { Name = "小旺" } };
foreach (var a in animals)
{
    Console.WriteLine($"{a.Name}: {a.Speak()}");
}
Output
?: ...
旺财: 汪汪
小旺: 嗷嗷

virtual allows overriding, override overrides, sealed stops it. Methods in C# are not overridable by default (unlike Java) and need explicit virtual — safer, since changing a base class cannot silently alter subclasses.

成员一览

MemberExample
字段private int _x;
属性public int X { get; set; }
方法public void Run()
构造函数public Foo()
静态构造static Foo()
索引器public T this[int i]
事件public event EventHandler E;
析构~Foo()(少用)

Friends & Partners