Procedura: utilizzare safe_cast in C++/CLI

Questo articolo illustra come usare safe_cast nelle applicazioni C++/CLI. Per informazioni sulle safe_cast in C++/CX, vedere safe_cast.

Upcasting

Un upcast è un cast da un tipo derivato a una delle relative classi di base. Questo cast è sicuro e non richiede una notazione cast esplicita. L'esempio seguente illustra come eseguire un upcast, con safe_cast e senza di esso.

// safe_upcast.cpp
// compile with: /clr
using namespace System;
interface class A {
   void Test();
};

ref struct B : public A {
   virtual void Test() {
      Console::WriteLine("in B::Test");
   }

   void Test2() {
      Console::WriteLine("in B::Test2");
   }
};

ref struct C : public B {
   virtual void Test() override {
      Console::WriteLine("in C::Test");
   };
};

int main() {
   C ^ c = gcnew C;

   // implicit upcast
   B ^ b = c;
   b->Test();
   b->Test2();

   // upcast with safe_cast
   b = nullptr;
   b = safe_cast<B^>(c);
   b->Test();
   b->Test2();
}
in C::Test
in B::Test2
in C::Test
in B::Test2

Downcasting

Un downcast è un cast da una classe base a una classe derivata dalla classe di base. Un downcast è sicuro solo se l'oggetto indirizzato in fase di esecuzione si rivolge effettivamente a un oggetto classe derivato. A differenza di static_cast, safe_cast esegue un controllo dinamico e genera InvalidCastException un'eccezione se la conversione non riesce.

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

interface class A { void Test(); };

ref struct B : public A {
   virtual void Test() {
      Console::WriteLine("in B::Test()");
   }

   void Test2() {
      Console::WriteLine("in B::Test2()");
   }
};

ref struct C : public B {
   virtual void Test() override {
      Console::WriteLine("in C::Test()");
   }
};

interface class I {};

value struct V : public I {};

int main() {
   A^ a = gcnew C();
   a->Test();
   B^ b = safe_cast<B^>(a);
   b->Test();
   b->Test2();

   V v;
   I^ i = v;   // i boxes V
   V^ refv = safe_cast<V^>(i);

   Object^ o = gcnew B;
   A^ a2= safe_cast<A^>(o);
}
in C::Test()
in C::Test()
in B::Test2()

safe_cast con conversioni definite dall'utente

Nell'esempio seguente viene illustrato come usare safe_cast per richiamare le conversioni definite dall'utente.

// safe_cast_udc.cpp
// compile with: /clr
using namespace System;
value struct V;

ref struct R {
   int x;
   R() {
      x = 1;
   }

   R(int argx) {
      x = argx;
   }

   static operator R::V^(R^ r);
};

value struct V {
   int x;
   static operator R^(V& v) {
      Console::WriteLine("in operator R^(V& v)");
      R^ r = gcnew R();
      r->x = v.x;
      return r;
   }

   V(int argx) {
      x = argx;
   }
};

   R::operator V^(R^ r) {
      Console::WriteLine("in operator V^(R^ r)");
      return gcnew V(r->x);
   }

int main() {
   bool fReturnVal = false;
   V v(2);
   R^ r = safe_cast<R^>(v);   // should invoke UDC
   V^ v2 = safe_cast<V^>(r);   // should invoke UDC
}
in operator R^(V& v
in operator V^(R^ r)

operazioni di safe_cast e boxing

Boxing

Il boxing viene definito come conversione definita dall'utente inserita dal compilatore. Pertanto, è possibile usare safe_cast per inserire un valore nell'heap CLR.

L'esempio seguente illustra il boxing con tipi valore semplici e definiti dall'utente. Esegue safe_cast il box di una variabile di tipo valore nello stack nativo in modo che possa essere assegnata a una variabile nell'heap sottoposto a Garbage Collection.

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

interface struct I {};

value struct V : public I {
   int m_x;

   V(int i) : m_x(i) {}
};

int main() {
   // box a value type
   V v(100);
   I^ i = safe_cast<I^>(v);

   int x = 100;
   V^ refv = safe_cast<V^>(v);
   int^ refi = safe_cast<int^>(x);
}

L'esempio seguente mostra che la conversione boxing ha priorità rispetto a una conversione definita dall'utente in un'operazione safe_cast .

// safe_cast_boxing_2.cpp
// compile with: /clr
static bool fRetval = true;

interface struct I {};
value struct V : public I {
   int x;

   V(int argx) {
      x = argx;
   }

   static operator I^(V v) {
      fRetval = false;
      I^ pi = v;
      return pi;
   }
};

ref struct R {
   R() {}
   R(V^ pv) {}
};

int main() {
   V v(10);
   I^ pv = safe_cast<I^>(v);   // boxing will occur, not UDC "operator I^"
}

Unboxing

Unboxing viene definito come conversione definita dall'utente inserita dal compilatore. Pertanto, è possibile usare safe_cast per annullare la posta in arrivo di un valore nell'heap CLR.

Unboxing è una conversione definita dall'utente, ma a differenza del boxing, unboxing deve essere esplicito, ovvero deve essere eseguito da un static_castcast in stile C o safe_cast; unboxing non può essere eseguito in modo implicito.

// safe_cast_unboxing.cpp
// compile with: /clr
int main() {
   System::Object ^ o = 42;
   int x = safe_cast<int>(o);
}

L'esempio seguente mostra unboxing con tipi valore e tipi primitivi.

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

interface struct I {};

value struct VI : public I {};

void test1() {
   Object^ o = 5;
   int x = safe_cast<Int32>(o);
}

value struct V {
   int x;
   String^ s;
};

void test2() {
   V localv;
   Object^ o = localv;
   V unboxv = safe_cast<V>(o);
}

void test3() {
   V localv;
   V^ o2 = localv;
   V unboxv2 = safe_cast<V>(o2);
}

void test4() {
   I^ refi = VI();
   VI vi  = safe_cast<VI>(refi);
}

int main() {
   test1();
   test2();
   test3();
   test4();
}

safe_cast e tipi generici

L'esempio seguente illustra come usare safe_cast per eseguire un downcast con un tipo generico.

// safe_cast_generic_types.cpp
// compile with: /clr
interface struct I {};

generic<class T> where T:I
ref struct Base {
   T t;
   void test1() {}
};

generic<class T> where T:I
ref struct Derived:public Base <T> {};

ref struct R:public I {};

typedef Base<R^> GBase_R;
typedef Derived<R^> GDerived_R;

int main() {
   GBase_R^ br = gcnew GDerived_R();
   GDerived_R^ dr = safe_cast<GDerived_R^>(br);
}

Vedi anche

safe_cast