How can I create .Net extension methods by C++/CLI

2019-02-04 10:15发布

In C#, extension methods can be created by

public static class MyExtensions {
    public static ReturnType MyExt(this ExtType ext) {
        ...
    }
}

Since all of my library are written in C++/CLI, I would like to create the .net extension methods also in C++/CLI (in order to have one DLL instead of two). I've tried the following code

static public ref class MyExtensions {
public:
    static ReturnType^ MyExt(this ExtType ^ext) {
        ...
    }
};

But the compiler can not recognize keyword 'this' in the first argument.

error C2059: syntax error: 'this'

Is there some way to create the extension method in C++/CLI ?

1条回答
爷的心禁止访问
2楼-- · 2019-02-04 10:45

You just have to decorate the method and the containing class with ExtensionAttribute:

using namespace System::Runtime::CompilerServices;
...

[ExtensionAttribute]
public ref class MyExtensions abstract sealed {
    public:        
        [ExtensionAttribute]
        static ReturnType MyExt(ExtType ^ext) {
            ...
        }
};
查看更多
登录 后发表回答