C++/CLI-Question: Is there an equivalent to the C# “is” keyword or do I have to use reflection?

后端 未结 3 1089
不知归路
不知归路 2021-01-01 23:38

I\'ve read somewhere on MSDN that the equivalent to C#\'s \"is\" keyword would be dynamic_cast, but that\'s not really equivalent: It doesn\'t work with value types or with

3条回答
  •  长发绾君心
    2021-01-02 00:13

    It's on MSDN:

    How to: Implement is and as C# Keywords in C++

    In a nutshell, you need to write a helper function like so:

    template < class T, class U > 
    Boolean isinst(U u) {
       return dynamic_cast< T >(u) != nullptr;
    }
    

    and call it like this:

    Object ^ o = "f";
    if ( isinst< String ^ >(o) )
        Console::WriteLine("o is a string");
    

提交回复
热议问题