如何将对象转换为通用列表我不知道C ++ / CLI中的类型参数?

时间:2015-05-26 10:25:31

标签: c# reflection c++-cli

我在MATLAB和C#之间编写胶水代码(我无法访问MATLAB出售的代码)。

我想将List<T>映射到特定的MATLAB结构(结构数组)。我在转换函数中有以下代码。

Object(实际上是List<MyClass>)转换为List<Object>会抛出InvalidCastException。

    // o is an C# Object I want to convert
    System::Type^ t = o->GetType();
    System::Type^ GenericListType = System::Collections::Generic::List<int>::typeid->GetGenericTypeDefinition();
    System::Type^ gt = t->IsGenericType ? t->GetGenericTypeDefinition() : nullptr;

    // ...

    // List<T> check
    else if (gt == GenericListType) {
        // map List<struct/class> to matlab struct array (export public fields only)
        // using actual matrix (dims != 1x1)
        // this save space as the fields name are stored only once

        // I can't cast to an explictit List<T> because T can be any class
        // but I need to know the list size

        // XXX: throws InvalidCastExceptions
        auto olist = (System::Collections::Generic::List<System::Object^>^)o; 
        const int count = olist->Count;

        if (count == 0) {
            System::Console::WriteLine("from_c_to_ml(): empty List<T>, returning nullptr, crash probably imminent, farewell my friends...");
            return nullptr;
        }

        // Now we need the actual type T (of List<T>) to know the public fields
        auto tlist = olist[0]->GetType();
        array<System::Reflection::FieldInfo^>^ fields = tlist->GetFields();
        const int fieldnb = fields->Length;

        // do stuff with it...
    }

1 个答案:

答案 0 :(得分:0)

转换为非通用List类型:

auto olist = (System::Collections::IList^)o;