How to check a generic type in C++/CLI?

2019-05-07 06:23发布

问题:

In C++/CLI code I need to check if the type is a specific generic type. In C# it would be:

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

but in cpp++\cli it does not work the same way, compiler shows the syntax error:

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

The best way I find is compare strings like this:

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

Does anybody know the better way?

PS: Is it limitation of typeof (typeid) in c++\cli or I do not know "correct" systax?

回答1:

You could write:

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