开发者

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

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 开发者_StackOverflow社区some way to create the extension method in C++/CLI ?


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) {
            ...
        }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜