使用 /clr 進行 C-Style 轉換 (C++/CLI)

下列主題僅適用於公用語言執行時間。

與CLR型別使用時,編譯器就會嘗試地圖c-style 轉型為其中一個轉換 (cast) 下, 面列出,順序如下:

  1. const_cast

  2. safe_cast

  3. safe_cast 加上 const_cast

  4. static_cast

  5. static_cast 加上 const_cast

如果無上面所列的轉型是否有效,以及如果運算式的型別和目標型別是CLR參考型別,c-style 轉換對應至執行階段-檢查 (castclass MSIL 指令)。否則,c-style 轉換會被視為不正確,則編譯器會發出錯誤。

備註

不建議 c-style 轉換。編譯與時/clr (Common Language Runtime 編譯),使用safe_cast (C++ 元件擴充功能)

下列範例會示範 c-style 轉換對應至const_cast。

// cstyle_casts_1.cpp
// compile with: /clr
using namespace System;

ref struct R {};
int main() {
   const R^ constrefR = gcnew R();
   R^ nonconstR = (R^)(constrefR); 
}

下列範例會示範 c-style 轉換對應至safe_cast

// cstyle_casts_2.cpp
// compile with: /clr
using namespace System;
int main() {
   Object ^ o = "hello";
   String ^ s = (String^)o;
}

下列範例會示範 c-style 轉換對應至safe_cast加上const_cast。

// cstyle_casts_3.cpp
// compile with: /clr
using namespace System;

ref struct R {};
ref struct R2 : public R {};

int main() {
   const R^ constR2 = gcnew R2();
   try {
   R2^ b2DR = (R2^)(constR2);
   }
   catch(InvalidCastException^ e) {
      System::Console::WriteLine("Invalid Exception");
   }
}

下列範例會示範 c-style 轉換對應至static_cast。

// cstyle_casts_4.cpp
// compile with: /clr
using namespace System;

struct N1 {};
struct N2 {
   operator N1() {
      return N1();
   }
};

int main() {
   N2 n2;
   N1 n1 ;
   n1 = (N1)n2;
}

下列範例會示範 c-style 轉換對應至static_cast加上const_cast。

// cstyle_casts_5.cpp
// compile with: /clr
using namespace System;
struct N1 {};

struct N2 {
   operator const N1*() {
      static const N1 n1;
      return &n1;
   }
};

int main() {
   N2 n2;
   N1* n1 = (N1*)(const N1*)n2;   // const_cast + static_cast
}

下列範例會示範 c-style 轉換對應至執行階段檢查。

// cstyle_casts_6.cpp
// compile with: /clr
using namespace System;

ref class R1 {};
ref class R2 {};

int main() {
   R1^ r  = gcnew R1();
   try {
      R2^ rr = ( R2^)(r);
   }
   catch(System::InvalidCastException^ e) {
      Console::WriteLine("Caught expected exception");
   }
}

下列範例會示範不正確c-style 轉換,而導致編譯器發出錯誤。

// cstyle_casts_7.cpp
// compile with: /clr
using namespace System;
int main() {
   String^s = S"hello";
   int i = (int)s;   // C2440
}

需求

編譯器選項:/clr

請參閱

概念

執行階段平台的元件擴充功能