如何:使用 C++ 实现 C# 的 is 和 as 关键字

更新:2007 年 11 月

本主题演示如何在 Visual C++ 中实现 is 和 as C# 关键字的功能。

有关更多信息,请参见is(C# 参考)as(C# 参考)

示例

// CS_is_as.cpp
// compile with: /clr
using namespace System;

interface class I {
public:
   void F();
};

ref struct C : public I {
   virtual void F( void ) { }
};

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

int main() {
   C ^ c = gcnew C();
   I ^ i = safe_cast< I ^ >(c);   // is (maps to castclass in IL)
   I ^ ii = dynamic_cast< I ^ >(c);   // as (maps to isinst in IL)

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

o is a string

请参见

其他资源

C++ 与其他 .NET 语言的互操作性