实现在C#/ C ++ / CLI中声明的接口 [英] Implementing an interface declared in C# from C++/CLI

查看:135
本文介绍了实现在C#/ C ++ / CLI中声明的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 IMyInterface 的C#界面,定义如下:

Say I have a C# interface called IMyInterface defined as follows:

// C# code
public interface IMyInterface
{
  void Foo(string value);
  string MyProperty { get; }
}

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

Assume I also have a C++/CLI class, MyConcreteClass, that implements this interface and whose header is declared as follows:

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

};

如何实现 Foo C / CLI头中的属性 MyProperty

How does one implement the method Foo and the property MyProperty in the C++/CLI header?

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

My attempt results in the following compile error:


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

error C3766: 'MyConcreteClass' must provide an implementation for the interface method 'void IMyInterface::Foo(System::String^ value)'


推荐答案

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

  virtual property String^ __clrcall MyProperty 
         { String^ get() sealed { String::Empty; } }
};

接口需要定义为虚拟。还要注意在类解散后的公共IMY ..,它是一个略微不同的语法比C#。

Interfaces need to be defined as virtual. Also note the "public IMy.." after the class decleration, it's a slighly different syntax than C#.

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

If you can, seal the interface members to improve performance, the compiler will be able to bind these methods more tightly than a typical virtual members.

希望有帮助;)

我没有编译它,但看起来不错我哦...还有, __clrcall消除双重thunk性能损失的危险。

I did not compile it but looks good to me... Oh and also, defining your methods as __clrcall eliminates dangers of double thunk performance penalties.

编辑
属性的正确语法为:

edit the correct syntax for a property is:

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

,或在源文件中定义时:

or, when putting the definition in the source file:

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^ )
{
  //...
}

这篇关于实现在C#/ C ++ / CLI中声明的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆