如何创建由C ++ / CLI的.Net扩展方法?方法、CLI、Net

2023-09-03 04:44:28 作者:繁華淡落、

在C#中,扩展方法可以通过

In C#, extension methods can be created by

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

由于所有的库是用C ++ / CLI,我想创建.NET扩展方法也是用C ++ / CLI(为了有一个DLL,而不是两个)。我已经试过以下code

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'

有没有一些方法来创建C ++ / CLI的扩展方法?

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

推荐答案

您只需要装饰方法和含有类ExtensionAttribute:

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