[英]How can I cast an Object to a generic List I don't know the type parameter of in C++/CLI?
I'm writing glue code between MATLAB and C# (I don't have access to the one sold by MATLAB). 我正在MATLAB和C#之间编写粘合代码(我无法访问MATLAB出售的代码)。
I want to map List<T>
to a particular MATLAB structure (array of structs). 我想将List<T>
映射到特定的MATLAB结构(结构数组)。 I have the following code in my conversion function. 我的转换函数中有以下代码。
Casting an Object
(which is actually a List<MyClass>
) to a List<Object>
throws an InvalidCastException. 将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...
}
强制转换为非通用List类型:
auto olist = (System::Collections::IList^)o;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.