代码:
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 关键字。
复制内容到剪贴板
代码:
sealed class CanNotbeTheParent
{
int a = 5;
}
unsafe
你可以使用 unsafe 修饰符在 C# 中定义一个不安全上下文。在不安全上下文中,你可以插入不安全代码,如 C++ 的指针等。参见以下代码:
复制内容到剪贴板
代码:
public unsafe MyFunction( int * pInt, double* pDouble)
{
int* pAnotherInt = new int;
*pAnotherInt = 10;
pInt = pAnotherInt;
...
*pDouble = 8.9;
}
接口
如果你有 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)
{
... // 做要做的事
}
// 类自身的方法
public void MoveShape(int newX, int newY)
{
.....
}
}
数组
数组在 C# 中比 C++ 中要高级很多。数组分配于堆中,所以是引用类型的。你不能访问数组边界外的元素。所以 C# 防止你引发那种 bug。同时也提供了迭代数组元素的帮助函数。foreach 是这样的迭代语句之一。C++ 和 C# 数组的语法差异在于:
方括号在类型后面而不是在变量名后面
创建元素使用 new 运算符
C# 支持一维、多维和交错数组(数组的数组)
例子:
复制内容到剪贴板
代码:
int[] array = new int[10]; // int 型一维数组
for (int i = 0; i < array.Length; i++)
array = i;
int[,] array2 = new int[5,10]; // int 型二维数组
array2[1,2] = 5;
int[,,] array3 = new int[5,10,5]; // int 型三维数组
array3[0,2,4] = 9;
int[][] arrayOfarray = new int[2]; // int 型交错数组 - 数组的数组
arrayOfarray[0] = new int[4];
arrayOfarray[0] = new int[] {1,2,15};

