/clr ile C Türü Atamalar (C++/CLI)

Aşağıdaki konu yalnızca Ortak Dil Çalışma Zamanı için geçerlidir.

CLR türleriyle kullanıldığında, derleyici C stili atamayı aşağıda listelenen tür türlerinden biriyle aşağıdaki sırayla eşlemeyi dener:

  1. Const_cast

  2. safe_cast

  3. safe_cast artı const_cast

  4. Static_cast

  5. static_cast artı const_cast

Yukarıda listelenen atamaların hiçbiri geçerli değilse ve ifadenin türü ve hedef türü CLR başvuru türleriyse, C stili atama çalışma zamanı denetimine (castclass MSIL yönergesi) eşlenir. Aksi takdirde, C stili atama geçersiz kabul edilir ve derleyici bir hata verir.

Açıklamalar

C stili atama önerilmez. /clr (Ortak Dil Çalışma Zamanı Derlemesi) ile derleme yaparken safe_cast kullanın.

Aşağıdaki örnekte, ile eşleyen C stili bir const_castyayın gösterilmektedir.

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

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

Aşağıdaki örnekte, bir safe_cast eşleyen C stili bir yayın gösterilmektedir.

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

Aşağıdaki örnekte, bir safe_cast artı const_castile eşleyen C stili bir yayın gösterilmektedir.

// 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");
   }
}

Aşağıdaki örnekte, ile eşleyen C stili bir static_castyayın gösterilmektedir.

// 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;
}

Aşağıdaki örnekte, artı const_castile eşleyen C stili bir static_cast yayın gösterilmektedir.

// 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
}

Aşağıdaki örnekte, çalışma zamanı denetimine eşleyen C stili bir yayın gösterilmektedir.

// 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");
   }
}

Aşağıdaki örnekte derleyicinin hata vermesine neden olan geçersiz bir C stili atama gösterilmektedir.

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

Gereksinimler

Derleyici seçeneği: /clr

Ayrıca bkz.

.NET ve UWP İçin Bileşen Uzantıları