c++cli 接口和实现中的静态 methods/properties 类

Static methods/properties in c++cli interface and implementation classes

我正在尝试为我在 c++cli 中拥有的 class 创建一个接口,然后在 c# 中使用它。

基本上,我想按照以下方式做一些事情:

public interface class IFoo
{
   static int method();

};

public ref class Foo : public IFoo
{
   static int method() { return 0; }   
};

所以显然这是不正确的,因为在尝试编译时会出现错误。我尝试了很多不同的方法,但都无济于事。

在 C# 中,我会执行以下操作:

public interface IFooCSharp
{
    int method();
}

public class FooCSharp : IFooCSharp
{
   public static int method() { return 0 };

   int IFooSharp.method() { return FooCSharp.method(); }
}

所以我希望看看在 c++cli 中是否有等效的方法来做到这一点?

接口中不能有静态成员。

您找到了在 C# 中执行此操作的正确方法:通过显式接口实现,您只需要 right syntax for C++/CLI:

public interface class IFoo
{
    int method();
};

public ref class Foo : public IFoo
{
    static int method() { return 0; }

    virtual int methodInterface() sealed = IFoo::method { return method(); }
};

与 C# 不同,您需要为您的方法提供一个名称,即使您不打算直接使用它。


属性语法如下:

public interface class IFoo
{
    property int prop;
};

public ref class Foo : public IFoo
{
    property int propInterface {
        virtual int get() sealed = IFoo::prop::get { return 0; }
        virtual void set(int value) sealed = IFoo::prop::set { /* whatever */ }
    };
};