Visual C++ .NET/Class/Casting

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Casting class

 
#include "stdafx.h"
using namespace System;
ref class A {};
ref class B : public A {};
ref class C {};
void main()
{
    Object ^v1 = gcnew A();              
    Object ^v2 = gcnew B();           
    Object ^v3 = gcnew C();         
    A ^a1 = gcnew A();               
    A ^a2 = gcnew B();
    A ^a3 = dynamic_cast<A^>(v1);  // downcast
    A ^a4 = dynamic_cast<A^>(v2);  // downcast
    B ^b1 = gcnew B();
    B ^b2 = dynamic_cast<B^>(v2);  // downcast
    B ^b4 = dynamic_cast<B^>(a2);  // downcast
    
    C ^c1 = gcnew C();
    C ^c2 = dynamic_cast<C^>(v1);  // Fails c2 = null. Miss match classes
    C ^c3 = static_cast<C^>(v2);   // c3 has invalid value of type B class
    C ^c4 = safe_cast<C^>(v3);     // downcast
    C ^c5 = (C^)(v3);              // downcast
}


Casting from object

 
#include "stdafx.h"
using namespace System;
using namespace System::Collections;
ref class Book{
   public:
     Book(){ }
     Book(String^ _title) { Title = _title; }
     property String^ Title;
};
int main(){
   ArrayList^ theList = gcnew ArrayList();
   theList->Add( gcnew Book("Men") );
   Book^ book = safe_cast<Book^>( theList[0] );
   Console::WriteLine(book->Title );
   theList->Add( gcnew String("data"));
   try{
      book = safe_cast<Book^>( theList[1] );
   }catch(InvalidCastException^ e){
      Console::WriteLine("wrong type");
   }
}


Checking casts

 
#include "stdafx.h"
using namespace System;
ref class Base {};
ref class Derived : Base {} ;
int main(){
    Base^ b = gcnew Base();
    Derived^ d = gcnew Derived();
    try
    {
       d = safe_cast<Derived^>(b);
    }
    catch (InvalidCastException^ e)
    {
    }
    
    d = dynamic_cast<Derived^>(b);
    if (d == nullptr)
    {
    }
}