C#笔记(二)---类型和成员

类声明 (class declarations)

A class declaration starts with a header. The header specifies:

  • 类的特性和修饰符
  • 类的名称
  • 基类(从基类继承时)
  • 接口由该类实现。

类型参数 (Type parameters)

例子:Pair 的类型参数是 TFirst 和 TSecond:

public class Pair<TFirst, TSecond>
{
    public TFirst First { get; }
    public TSecond Second { get; }
    
    public Pair(TFirst first, TSecond second) => 
        (First, Second) = (first, second);
}
// How to use
var pair = new Pair<int, string>(1, "two");

基类 (Base classes)

类声明可以指定基类。 在类名和类型参数后面加上冒号和基类的名称。 省略基类规范与从 object 类型派生相同。

public class Point3D : Point
{
    public int Z { get; set; }
    
    public Point3D(int x, int y, int z) : base(x, y)
    {
        Z = z;
    }
}

类继承其基类的成员。 继承意味着一个类隐式包含其基类的几乎所有成员。 类不继承实例、静态构造函数以及终结器。(instance and static constructors, and the finalizer)

结构(Struct)

结构类型是较为简单的类型,其主要目的是存储数据值*。 结构不能声明基类型.
struct implicitly derive from System.ValueType. You can't derive other struct types from a struct type. They're implicitly sealed.

public struct Point{...}

接口

接口定义了可由类和结构实现的协定。 接口可以包含方法、属性、事件和索引器。 接口通常不提供所定义成员的实现,仅指定必须由实现接口的类或结构提供的成员。

接口可以采用“多重继承”。类和结构可以实现多个接口。

当类或结构实现特定接口时,此类或结构的实例可以隐式转换成相应的接口类型。

枚举

例子:

public enum SomeRootVegetable
{
    HorseRadish,
    Radish,
    Turnip
}
public enum Seasons
{
    None = 0,
    Summer = 1,
    Autumn = 2,
    Winter = 4,
    Spring = 8,
    All = Summer | Autumn | Winter | Spring
}

可为 null 的类型

任何类型的变量都可以声明为“不可为 null”或“可为 null” 。 可为 null 的变量包含一个额外的 null 值,表示没有值。

可为 null 的值类型(结构或枚举)由 System.Nullable 表示。

不可为 null 和可为 null 的引用类型都由基础引用类型表示。

这种区别由编译器和某些库读取的元数据体现。 当可为 null 的引用在没有先对照 null 检查其值的情况下取消引用时,编译器会发出警告。 当对不可为 null 的引用分配了可能为 null 的值时,编译器也会发出警告。

int? optionalInt = default; 
optionalInt = 5;
string? optionalText = default;
optionalText = "Hello World.";

元组(Tuples)

(double Sum, int Count) t2 = (4.5, 3);
原文地址:https://www.cnblogs.com/francisforeverhappy/p/Csharp2.html