c++-cli - C++/CLI-问题 : Is there an equivalent to the C# "is" keyword or do I have to use reflection?

标签 c++-cli

我在 MSDN 上的某个地方读到过,与 C# 的“is”关键字等效的是 dynamic_cast,但这并不是真正等效的:它不适用于值类型或泛型参数。例如在 C# 中,我可以写:

void MyGenericFunction<T>()
{
    object x = ...
    if (x is T)
        ...;
}

如果我尝试“等效”C++/CLI:
generic<class T>
void MyGenericFunction()
{
    object x = ...
    if (dynamic_cast<T>(x))
       ...;
}

我收到编译器错误“错误 C2682:无法使用 'dynamic_cast' 从 'System::Object ^' 转换为 'T'”。

我唯一能想到的就是使用反射:
if (T::typeid->IsAssignableFrom(obj->GetType()))

有没有更简单的方法来做到这一点?

最佳答案

它在 MSDN 上:

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

简而言之,您需要像这样编写一个辅助函数:

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

并这样称呼它:
Object ^ o = "f";
if ( isinst< String ^ >(o) )
    Console::WriteLine("o is a string");

关于c++-cli - C++/CLI-问题 : Is there an equivalent to the C# "is" keyword or do I have to use reflection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/712845/

相关文章:

visual-studio-2010 - 我是否需要在 C++/CLI 中对 IDisposable 对象调用 delete

winforms - 错误 C2039 : 'Dispose' : is not a member of 'System::Windows::Forms::ErrorProvider'

visual-c++ - 两个类对​​象之间的 Visual C++/CLI 相互访问?

arrays - 来自指针的 std::array 或 std::vector

c# - 在 C# 对象上调用 C++/CLI delete

visual-studio - 为什么是 Intellisense "Unavailable for C++/CLI"?

c# - 调用 C++/CLI 包装器时出现外部异常 E0434352

c++ - 无论崩溃如何保存日志文本文件

c++-cli - 为什么不能将跟踪引用用作类成员?

visual-c++ - Visual C++/CLI - CLR 类 - LNK2020 错误 - 如何修复?