首页 >> 民生新闻

程序员在学习时需要注意的一些问题一覆盖

民生新闻  2021-08-24 13:28 字号: 大 中 小

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()

{

iteLine(\"MyCar run, at speed {0}\", _speed);

}

public void Stop()

{

iteLine(\"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 ngth; 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)

{

iteLine(\"number of elements {0}\", ngth);

}

}

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)

{

iteLine(\"obj is MyCar object\");

ICar ic = obj as ICar;

eed = 999;

n();

op();

}

else

{

iteLine(\"obj is not MyCar object\");

}

}

}

7)foreach

int []arr = new int[10];

foreach(int i in arr)

iteLine(\"{0}\", i);

8)virtual and override

子类重载父类虚函数,需要使用override关键字。

class BaseClass

{

public virtual void Speak()

{

iteLine(\"Hello, BaseClass.\");

}

}

class Son : BaseClass

{

public override void Speak()

{

iteLine(\"Hello, Son.\");

}

}

class GrandSon : BaseClass

{

public override void Speak()

{

iteLine(\"Hello, GrandSon.\");

}

}

9)使用关键字new隐藏父类的函数实现

class Shape

{

public virtual void Draw()

{

iteLine(\"aw\") ;

}

}

class Rectangle : Shape

{

public new void Draw()

{

iteLine(\"aw\");

}

}

class Square : Rectangle

{

public new void Draw()

{

iteLine(\"aw\");

}

}

10)调用父类中的函数

使用关键字base来调用父类中的函数。

class Father

{

public void Hello()

{

iteLine(\"Hello!\");

}

}

class Child : Father

{

public new void Hello()

{

llo();

}

}

铝门窗哪个品牌质量好
玉溪白斑疯医院
天津专治白癜风医院
推荐资讯