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

How can I cast an Object to a generic List I don't know the type parameter of in 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...
    }

转换为非通用列表类型有效:

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