3

我想将该行从 c# 转换为 c++/cli

Idocobj is IPart

IPart 是一个接口,Idocobj 是一个对象。有没有办法进行这种转换。

我使用了这段代码:

Idocobj->GetType() == IPart::typeid 

但它不起作用

4

1 回答 1

3

您可以使用dynamic_cast来检查“是”。这是一个例子:

using namespace System;
namespace NS
{
  public interface class IFoo
  {
    void Test();
  };

  public ref class Foo : public IFoo
  {
  public: virtual void Test() {}
  };
  public ref class Bar
  {
  public: virtual void Test() {}
  };
}

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

int main()
{
    NS::Foo^ f = gcnew NS::Foo();
    NS::Bar^ b = gcnew NS::Bar();

    if (isinst<NS::IFoo^>(f))
      Console::WriteLine("f is IFoo");

    if (isinst<NS::IFoo^>(b) == false)
      Console::WriteLine("f is not IFoo");

    Console::ReadKey();
}

但是通常,您从不使用“is”....您总是想对检查做一些事情...所以通常您应该使用“as”直接映射到dynamic_cast

NS::IFoo^ ifoo = dynamic_cast<NS::IFoo^>(f);
if (ifoo != nullptr)
{
  // Do something...
 ifoo->Test();
}
于 2013-07-16T08:30:32.557 回答