在 C# 继承语法中,冒号 (:) 的主要用途是指定继承关系,它有多种重要用途:
1. 指定基类(继承)
public class Animal { }
public class Dog : Animal { } // Dog 继承 Animal2. 实现接口
public interface IDisposable { }
public class MyClass : IDisposable { } // 实现接口3. 同时继承类和实现接口
public class Animal { }
public interface IRunnable { }
public interface ISwimmable { }
public class Duck : Animal, IRunnable, ISwimmable { }
// 先基类,后接口,用逗号分隔4. 调用基类构造函数
public class Animal
{
public Animal(string name) { }
}
public class Dog : Animal
{
public Dog(string name) : base(name) { } // 调用基类构造函数
}5. 调用当前类其他构造函数
public class Person
{
public Person(string name) { }
public Person() : this("Unknown") { } // 调用本类其他构造函数
}6. 完整的语法结构
[访问修饰符] class 派生类名 : 基类名, 接口1, 接口2, ...
{
// 构造函数可以这样调用基类构造
public 派生类名(参数) : base(参数) { }
// 或者调用本类其他构造
public 派生类名() : this(默认值) { }
}实际示例
// 基类
public class Vehicle
{
protected string _brand;
public Vehicle(string brand) => _brand = brand;
}
// 接口
public interface IEngine { void Start(); }
// 派生类
public class Car : Vehicle, IEngine
{
public Car(string brand) : base(brand) { } // 调用基类构造
public void Start() => Console.WriteLine("Engine started");
}总结冒号的用途:
类 : 基类- 继承关系类 : 接口- 实现接口类 : 基类, 接口1, 接口2- 继承+实现构造函数() : base()- 调用基类构造构造函数() : this()- 调用本类其他构造
冒号在继承语法中起着连接和指定的关键作用,它建立了类与类、类与接口之间的各种关系。