2011-06-17 23 views
4

在C++/CLI代码中,我需要检查类型是否是特定的泛型类型。在C#这将是:如何检查C++/CLI中的泛型类型?

public static class type_helper { 
    public static bool is_dict(Type t) { 
     return t.IsGenericType 
      && t.GetGenericTypeDefinition() == typeof(IDictionary<,>); 
    } 
} 

但CPP ++ \ CLI不相同的方式工作,编译器显示了语法错误:

class type_helper { 
public: 
    static bool is_dict(Type^ t) { 
     return t->IsGenericType && t->GetGenericTypeDefinition() 
      == System::Collections::Generic::IDictionary<,>::typeid; 
    } 
}; 

,我觉得最好的办法是比较喜欢这样的字符串:

class type_helper { 
public: 
    static bool is_dict(Type^ t) { 
     return t->IsGenericType 
      && t->GetGenericTypeDefinition()->Name == "IDictionary`2"; 
    } 
}; 

有没有人知道更好的方法?

PS: 它是在C++ \ cli中typeof(typeid)的限制还是我不知道“正确的”systax?

+0

“编译器显示了语法错误” - 是什么语法错误? –

+0

对不起,我没有第一次说。它是: 1> test.cpp(4):错误C2059:语法错误:',' –

回答

6

你可以写:

return t->IsGenericType 
    && t->GetGenericTypeDefinition() == System::Collections::Generic::IDictionary<int,int>::typeid->GetGenericTypeDefinition(); 
+0

好主意!谢谢! –