Sealed Class
sealed 禁止任何类从其派生,例如string类也可用于重载方法
Virtual
C#支持对属性和方法的重写,不支持字段和静态成员
用
virtual 关键字修饰基类中被重写的方法,override 修饰重写后的方法使用override重写后,虚成员会默认调用 ”most derived implementation”
// Contact : Item Item item; Contact contact; contact = new Contact(); item = contact; item.virtualMethod(); // Call the implementation of "Contact" indeed
new V.S. override
override如上所述
new关键字修饰成员时,表明隐藏其基类成员。通过基类引用调用该成员时,仍调用基类的方法(静态类型only,dynamic修饰的动态类型反之)
派生类的同名方法默认为new
namespace TestUse; public class Program { public class BaseClass { public void Display() { Console.WriteLine("BaseClass"); } } // Compiler WARNING // Display' 上需要关键字 'new',因为它会隐藏方法 'void TestUse.Program.BassClass.Display()' public class DerivedClass : BaseClass { public virtual void Display() { Console.WriteLine("DerivedClass"); } } public class SubDerivedClass : DerivedClass { public override void Display() { Console.WriteLine("SubDerivedClass"); } } public class SuperSubDerivedClass : SubDerivedClass { public new void Display() { Console.WriteLine("SuperSubDerivedClass"); } } public static void Main() { SuperSubDerivedClass superSubDerivedClass = new SuperSubDerivedClass(); SubDerivedClass subDerivedClass = superSubDerivedClass; DerivedClass derivedClass = superSubDerivedClass; BaseClass baseClass = superSubDerivedClass; superSubDerivedClass.Display(); subDerivedClass.Display(); derivedClass.Display(); baseClass.Display(); } } /* SuperSubDerivedClass SubDerivedClass SubDerivedClass BaseClass */
所有类的基类:System.Object
甚至字面值也支持
System.Object 的方法Console.WriteLine(42.ToString());
无论显式继承
object 与否,生成的CIL代码都相同is
用于模式匹配
可匹配类型、常量、var
if (data is "") { // ... } // switch ... else (GetObjectById(id) is var result) { // Equal to var result = GetObjectById(id) }
C#8.0后:元组、按序、属性、递归模式匹配
// 元组 if ((args.Length, args[Actor] is (1, "show")){} // 按序 // 对类的解构函数进行匹配 if (person is (string firstname, string lastname) {} // 属性 // 同按序,但是可以指定属性名字 // 假定person的Deconstruct方法的out参数为 // firstname和lastname person is {firstname: string firstname, lastnae: string lastname} // 递归可以认为是上述模式匹配的组合
switch expression (C# 8.0)
下面这段代码即为switch expression的使用
其会将switch关键字前面的变量与大括号内的类型进行匹配,并返回一个可空元组
(int Year, int Month, int Day)? is {} date 用于检查switch expression是否非空,是则将返回值命名为date,进行后续操作public static string? CompositeFormatDate(object input, string CompositeFormatString) { input switch { DateTime { Year: int year, Month: int month, Day: int day } => (year, month, day), DateTimeOffset { Year: int year, Month: int month, Day: int day } => (year, month, day), string dateText => DateTime.TryParse(dateText, out DateTime dateTime) ? (dateTime.Year, dateTime.Month, dateTime.Day) : default((int Year, int Month, int Day)?), _ => null } is {} date ? string.Format(CompositeFormatString, date.Year, date.Month, date.Day) : null; }