1、顯式轉換和隱式轉換:
int a=123; long b=a; // 從int到long的隱式轉換 int c=(int) b; // 從long到int是顯式轉換 --------------------------------------------------------- class Base{} class Derived:Base{} class Program { static void Main(string[] args) { Base myBaseType; // 派生類向基類的隱式強制類型轉換 myBaseType = new Derived (); // 在派生類型中存儲基類引用必須顯式強制類型轉換 Derived myDerivedType= (Derived)myBaseType ; } }
2、創建自定義轉換例程
public static explicit operator xx類 (yy類 y) { xx類 x= new xx類(); y.porp =x.porp; return x; }
1)使用operator關鍵字
2)operator結合使用explicit或implicit關鍵字
3)方法必須定義為靜態的
4)傳入的參數y是要轉換的實例,而操作符類型是轉換后的實例
5)explicit顯式轉換
6)implicit隱式轉換