C++ cli 从C+实现在C#中声明的接口+/CLI
假设我有一个名为C++ cli 从C+实现在C#中声明的接口+/CLI,c++-cli,C++ Cli,假设我有一个名为IMyInterface的C#接口,定义如下: // C# code public interface IMyInterface { void Foo(string value); string MyProperty { get; } } // C++/CLI header file ref class MyConcreteClass : IMyInterface { public: }; 假设我还有一个C++/CLI类,MyConcreteClass,它实现了这个
IMyInterface
的C#接口,定义如下:
// C# code
public interface IMyInterface
{
void Foo(string value);
string MyProperty { get; }
}
// C++/CLI header file
ref class MyConcreteClass : IMyInterface
{
public:
};
假设我还有一个C++/CLI类,MyConcreteClass
,它实现了这个接口,其头声明如下:
// C# code
public interface IMyInterface
{
void Foo(string value);
string MyProperty { get; }
}
// C++/CLI header file
ref class MyConcreteClass : IMyInterface
{
public:
};
如何在C++/CLI头中实现方法Foo
和属性MyProperty
我的尝试导致以下编译错误:
错误C3766:“MyConcreteClass”必须
为
界面法的void
IMyInterface::Foo(系统::字符串^
价值)'
接口需要定义为虚拟接口。还要注意在类declaration之后的“public IMy..”,它的语法与C#略有不同
如果可以,密封接口成员以提高性能,编译器将能够比典型的虚拟成员更紧密地绑定这些方法
希望有帮助;)
我没有编译它,但看起来不错。。。哦,而且,将方法定义为_clrcall可以消除双重thunk性能惩罚的危险
编辑
属性的正确语法为:
public ref class MyConcreteClass : public IMyInterface
{
public:
virtual property String^ MyProperty
{
String^ get() sealed { return String::Empty; };
void set( String^ s ) sealed { };
}
};
或者,将定义放入源文件时:
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^ )
{
//...
}
谢谢你。MyProperty声明是否不需要'property'关键字?如。。。虚拟财产字符串^MyProperty{String^\uuu clrcall get()sealed{return String::Empty;}}谢谢Simon,我一定是在这场长达30小时的马拉松式编码中被盯上了!!=)因为这是谷歌的第一个热门话题之一,我用正确的属性语法编辑了答案,这有点棘手。@stijn我不相信关键字
sealed
仅仅是语法所必需的,或者是吗?@Herzube确实不是(除非你想密封属性),我把它包括进去,因为原来的答案已经有了