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

不打扰是莪最后的温柔 提交于 2019-11-29 06:38:02

问题


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:


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


来源:https://stackoverflow.com/questions/6012578/how-can-i-create-net-extension-methods-by-c-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!