从C++/CLI实现在C#中声明的接口

Sim*_*win 34 c++-cli

假设我有一个名为C#的接口IMyInterface定义如下:

// C# code
public interface IMyInterface
{
  void Foo(string value);
  string MyProperty { get; }
}
Run Code Online (Sandbox Code Playgroud)

假设我还有一个C++/CLI类MyConcreteClass,它实现了这个接口,其头部声明如下:

// C++/CLI header file
ref class MyConcreteClass : IMyInterface
{
public:

};
Run Code Online (Sandbox Code Playgroud)

如何在C++/CLI头中实现方法Foo和属性MyProperty

我的尝试导致以下编译错误:

错误C3766:'MyConcreteClass'必须为接口方法提供一个实现'void IMyInterface :: Foo(System :: String ^ value)'

Ran*_*e42 37

public ref class MyConcreteClass : public IMyInterface
{
 public:
  virtual void __clrcall Foo(String^ value) sealed;  

  virtual property String^ __clrcall MyProperty 
         { String^ get() sealed { String::Empty; } }
};
Run Code Online (Sandbox Code Playgroud)

接口需要定义为虚拟.在课堂变换之后还要注意"公共IMy ..",它的语法与C#略有不同.

如果可以,密封接口成员以提高性能,编译器将能够比典型的虚拟成员更紧密地绑定这些方法.

希望有所帮助;)

我没有编译它但对我来说看起来很好......哦,并且,将__clrcall定义为方法可以消除双重性能损失的危险.

编辑 属性的正确语法是:

public ref class MyConcreteClass : public IMyInterface
{
 public:
  virtual property String^ MyProperty 
  {
    String^ get() sealed { return String::Empty; };
    void set( String^ s ) sealed { };
  }
};
Run Code Online (Sandbox Code Playgroud)

或者,当将定义放在源文件中时:

public ref class MyConcreteClass : public IMyInterface
{
 public:
  virtual property String^ MyProperty 
  {
    String^ get() sealed;
    void set( String^ s ) sealed;
  }
};

String^ MyConcreteClass::MyProperty::get()
{
  return String::Empty;
}

void MyConcreteClass::MyProperty::set( String^ )
{
  //...
}
Run Code Online (Sandbox Code Playgroud)

  • 由于这是 google 中的第一批命中之一,因此我使用正确的属性语法编辑了答案,这有点棘手。 (2认同)