本文講述的是c++程序員在學習c#時需要注意的一些問題。
c++程序員在學習c#時需要注意的一些問題(一)
1)使用接口(interface)
在c#中,使用關鍵字interface來定義接口;而且,在c#中不能使用多重繼承。
interface icar//接口icar
{
int speed//屬性speed
{
get;
set;
}
void run();//接口方法
void stop();
}
class mycar : icar //繼承接口
{
int _speed;
public int speed
{
get
{
return _speed;
}
set
{
_speed = value;
}
}
public void run()
{
system.console.writeline("mycar run, at speed {0}", _speed);
}
public void stop()
{
system.console.writeline("mycar stop.");
}
}
2)使用數組
c#中的數組在堆中分配,因此是引用類型。c#支持3中類型的數組:一維數組(single dimensional),多維數組(multi dimensional)和數組的數組(array of array)。
int[] array = new int[10]; // single-dimensional array of int
for (int i = 0; i < array.length; i++)
array[i] = i;
int[ ,] array2 = new int[5,10]; // 2-dimensional array of int
array2[1,2] = 5;
int[ , , ] array3 = new int[5,10,5]; // 3-dimensional array of int
array3[0,2,4] = 9;
int[][] arrayofarray = new int[2]; // array of array of int
arrayofarray[0] = new int[4];
arrayofarray[0] = new int[] {1,2,15};
3)使用索引(indexer)
索引使得可以像訪問數組一樣來訪問類數據。
class indextest
{
private int[] _a;
public indextest()
{
_a = new int[10];
}
public int this[int index]
{
get
{
return _a[index];
}
set
{
_a[index] = value;
}
}
}
4)一般參數傳遞
class passarg
{
public void byvalue(int x)//by-value
{
x = 777;
}
public void byref(ref int x)//by-ref
{
x = 888;
}
public void byout(out int x)//out
{
x = 999;
}
}
5)傳遞數組參數
使用params關鍵字來傳遞數組參數。
class arraypass
{
public void func(params int[] array)
{
console.writeline("number of elements {0}", array.length);
}
}
6)is 和 as
obj is class用于檢查對象obj是否是屬于類class的對象或者convertable。
obj as class用于檢查對象obj是否是屬于類class的對象或者convertable,如果是則做轉換操作,將obj轉換為class類型。
class isas
{
public void work(object obj)
{
if(obj is mycar)
{
system.console.writeline("obj is mycar object");
icar ic = obj as icar;
ic.speed = 999;
ic.run();
ic.stop();
}
else
{
system.console.writeline("obj is not mycar object");
}
}
}
7)foreach
int []arr = new int[10];
foreach(int i in arr)
console.writeline("{0}", i);
8)virtual and override
子類重載父類虛函數,需要使用override關鍵字。
class baseclass
{
public virtual void speak()
{
system.console.writeline("hello, baseclass.");
}
}
class son : baseclass
{
public override void speak()
{
system.console.writeline("hello, son.");
}
}
class grandson : baseclass
{
public override void speak()
{
system.console.writeline("hello, grandson.");
}
}
9)使用關鍵字new隱藏父類的函數實現
class shape
{
public virtual void draw()
{
console.writeline("shape.draw") ;
}
}
class rectangle : shape
{
public new void draw()
{
console.writeline("rectangle.draw");
}
}
class square : rectangle
{
public new void draw()
{
console.writeline("square.draw");
}
}
10)調用父類中的函數
使用關鍵字base來調用父類中的函數。
class father
{
public void hello()
{
system.console.writeline("hello!");
}
}
class child : father
{
public new void hello()
{
base.hello();
}
}
新聞熱點
疑難解答