C# Syntax base++

2021-07-08 16:08

阅读:516

标签:func   port   参考   tps   paint   div   pes   length   and   

structs

Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type ValueType, which in turn implicitly inherits from object.

struct Point {
    public int x, y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

// use the struct
Point a = new Point(10, 10);
Point b = a;
a.x = 20;
Console.WriteLine(b.x);

如果 Point 是类,则输出 20,因为 a 和 b 引用同一对象。 如果 Point 是结构,则输出 10,因为将 a 赋值给 b 创建了值副本,而此副本不受后面对 a.x 的赋值的影响。

以上示例突出显示了结构的两个限制。 首先,复制整个结构通常比复制对象引用效率更低,因此通过结构进行的赋值和值参数传递可能比通过引用类型成本更高。 其次,除 inref 和 out 参数以外,无法创建对结构的引用,这就表示在很多应用场景中都不能使用结构。

Arrays

数组类型是引用类型,声明数组变量只是为引用数组实例预留空间。 实际的数组实例是在运行时使用 new 运算符动态创建而成。 new 运算指定了新数组实例的长度,然后在此实例的生存期内固定使用这个长度。 数组元素的索引介于 0 到 Length - 1 之间。 new 运算符自动将数组元素初始化为其默认值(例如,所有数值类型的默认值为 0,所有引用类型的默认值为 null)。

int[] a1 = new int[10];
int[,] a2 = new int[10, 5];
int[,,] a3 = new int[10, 5, 2];

数组的元素类型可以是任意类型(包括数组类型)。 包含数组类型元素的数组有时称为交错数组,因为元素数组的长度不必全都一样。 以下示例分配由 int 数组构成的数组:

int[][] a = new int[3][];
a[0] = new int[10];
a[1] = new int[5];
a[2] = new int[20];

Interfaces

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

接口可以采用多重继承

类和结构可以实现多个接口。

一般情况下,实现类都是以public的方式实现接口中的方法。 C# 还支持显式接口成员实现代码,这样类或结构就不会将成员设为公共成员。 显式接口成员实现代码是使用完全限定的接口成员名称进行编写。如下示例:

public class EditBox: IControl, IDataBound
{
    void IControl.Paint() { }
    void IDataBound.Bind(Binder b) { }
}

显式接口成员只能通过接口类型进行访问。 例如,只有先将 EditBox 引用转换成 IControl 接口类型,才能调用上面 EditBox 类提供的 IControl.Paint 实现代码。

EditBox editBox = new EditBox();
editBox.Paint();            // Error, no such method
IControl control = editBox;
control.Paint();            // Ok

通过直接使用接口,您不会将代码耦合到底层实现。同样,显式接口实现处理命名或方法签名的模糊性 - 并使单个类可以实现具有相同成员的多个接口。

关于“显式接口实现”的具体使用和注意事项,请参考《C#: Favorite Features through the Years》的第一节:C# Version 1.0

 

 

 

 

 

C# Version 1.0

C# Syntax base++

标签:func   port   参考   tps   paint   div   pes   length   and   

原文地址:https://www.cnblogs.com/brt3/p/9735140.html


评论


亲,登录后才可以留言!