日期:2011-05-19  浏览次数:20486 次

本文讲述的是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
 {
  p