C ++ / CLI中的通用类型定义

时间:2012-08-06 14:12:47

标签: generics c++-cli

在C#中可以写

typeof(IInterface<>).

C ++ / CLI中是否有类似内容?

ISYMessageDispatcher<>::typeid

无法编译,因为编译器崩溃。

enter image description here

2 个答案:

答案 0 :(得分:1)

当我测试它时(使用Visual Studio 2010 SP1),这不会使编译器崩溃,它只是一个语法错误。

#using <System.dll>

int main(void)
{
    System::Console::WriteLine( (System::Collections::Generic::List<>::typeid)->ToString() );
    return 0;
}

尝试编译给出:

Microsoft (R) C/C++ Optimizing Compiler Version 16.00.40219.01
for Microsoft (R) .NET Framework version 4.00.30319.269
Copyright (C) Microsoft Corporation.  All rights reserved.

generictypeid.cpp
generictypeid.cpp(5) : error C2976: 'System::Collections::Generic::List' : too few generic arguments
        c:\windows\microsoft.net\framework\v4.0.30319\mscorlib.dll : see declaration of 'System::Collections::Generic::List'

要获得解决方法,请参阅my answer to a related question "How to check a generic type in C++/CLI?"

答案 1 :(得分:0)

以下适用于我:

auto x = gcnew Generic::List<bool>;
if (x->GetType()->GetGenericTypeDefinition() == Generic::List::typeid)
{
   System::Console::WriteLine("The generic type is " + Generic::List::typeid); // or x->GetType::GetGenericTypeDefinition()
   System::Console::WriteLine("The specific type is " + Generic::List<bool>::typeid); // or x->GetType()
}

这会产生输出

  

泛型类型是System.Collections.Generic.List`1 [T]

     

具体类型是System.Collections.Generic.List`1 [System.Boolean]