-------------------
修饰符
-------------------
你必须已经知道 public 、 private 、 protected 这些常在 C++ 当中使用的修饰符。这里我会讨论一些 C# 引入的新的修饰符。
** readonly (只读) **
readonly 修饰符仅在类的数据成员中使用。正如这名字所提示的, readonly 数据成员仅能只读,它们只能在构造函数或是直接初始化操作下赋值一次。 readonly 与 const 数据成员不同, const 要求你在声明中初始化,这是直接进行的。看下面的示例代码:
class MyClass
{
const int constInt = 100; // 直接初始化
readonly int myInt = 5; // 直接初始化
readonly int myInt2; // 译者注:仅做声明,未做初始化
public MyClass()
{
myInt2 = 8; // 间接的
}
public Func()
{
myInt = 7; // 非法操作(译者注:不得赋值两次)
Console.WriteLine(myInt2.ToString());
}
}
** sealed (密封) **
密封类不允许任何类继承,它没有派生类。因此,你可以对你不想被继承的类使用 sealed 关键字。
sealed class CanNotbeTheParent
{
int a = 5;
}
uns afe (不安全)
你可使用 unsafe 修饰符来定义一个不安全的上下文。在不安全的上下文里,你能写些如 C++ 指针这样的不安全的代码。看下面的示例代码:
public unsafe MyFunction( int * pInt, double* pDouble)
{
int* pAnotherInt = new int;
*pAnotherInt = 10;
pInt = pAnotherInt;
...
*pDouble = 8.9;
}
-------------------
** interface (接口) **
-------------------
如果你有 COM 方面的概念,你会立亥明白我要谈论的内容。一个接口就是一个抽象的基类,这个基类仅仅包含功能描述,而这些功能的实现则由子类来完成。 C# 中你要用 interface 关键字来定义象接口这样的类。 .NET 就是基于这样的接口上的。 C# 中你不支持 C++ 所允许的类多继承(译者注:即一个派生类可以从两个或两个以上的父类中派生)。但是多继承方式可以通过接口获得。也就是说你的一个子类可以从多个接口中派生实现。
using System;
interface myDrawing
{
int originx
{
get;
set;
}
int originy
{
get;
set;
}
void Draw(object shape);
}
class Shape: myDrawing
{
int OriX;
int OriY;
public int originx
{
get{
return OriX;
}
set{
OriX = value;
}
}
public int originy
{
get{
return OriY;
}
set{
OriY = value;
}
}
public void Draw(object shape)
{
... // do something
}
// class's own method
public void MoveShape(int newX, int newY)
{
.....
}
}
-------------------
** Arrays (数组) **
-------------------
C# 中的数组比 C++ 的表现更好。数组被分配在堆中,因此是引用类型。你不可能访问超出一个数组边界的元素。因此, C# 会防止这样类型的 bug 。一些辅助方式可以循环依次访问数组元素的功能也被提供了, foreach 就是这样的一个语句。与 C++ 相比, C# 在数组语法上的特点如下:
方括号被置于数据类型之后而不是在变量名之后。
创建数组元素要使用 new 操作符。
C# 支持一维、多维以及交错数组(数组中的数组)。
示例:
int[] array = new int[10]; // 整型一维数组
for (int i = 0; i < array.Length; i++)
array[i] = i;
int[,] array2 = new int[5,10]; // 整型二维数组
array2[1,2] = 5;
int[,,] array3 = new int[5,10,5]; // 整型的三维数组
array3[0,2,4] = 9;
int[][] arrayOfarray = = new int[2]; // 整型交错数组(数组中的数组)
arrayOfarray[0] = new int[4];
arrayOfarray[0] = new int[] {1,2,15};
-------------------
索引器
-------------------
索引器被用于写一个访问集合元素的方法,集合使用 "[]" 这样的直接方式,类似于数组。你所要做的就是列出访问实例或元素的索引清单。类的属性带的是输入参数,而索引器带的是元素的索引表,除此而外,他们二者的语法相同。
示例:
注意: CollectionBase 是一个制作集合的库类。 List 是一个 protected 型的 CollectionBase 成员,储存着集合清单列表。
class Shapes: CollectionBase
{
public void add(Shape shp)
{
List.Add(shp);
}
//indexer
public Shape this[int index]
{
get {
return (Shape) List[index];
}
set {
List[index] = value ;
}
}
}