C# 自定義類型轉換


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隱式轉換


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM