.net - 如何通过C++/CLI创建.Net扩展方法?

标签 .net c++-cli extension-methods

在C#中,扩展方法可以通过以下方式创建

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

由于我的所有库都是用C++ / CLI编写的,因此我也想在C++ / CLI中创建.net扩展方法(以便使用一个DLL而不是两个DLL)。我尝试了以下代码
static public ref class MyExtensions {
public:
    static ReturnType^ MyExt(this ExtType ^ext) {
        ...
    }
};

但是编译器无法在第一个参数中识别关键字“this”。
error C2059: syntax error: 'this'

有什么方法可以在C++ / CLI中创建扩展方法?

最佳答案

您只需要用ExtensionAttribute装饰方法和包含的类:

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

[ExtensionAttribute]
public ref class MyExtensions abstract sealed {
    public:        
        [ExtensionAttribute]
        static ReturnType MyExt(ExtType ^ext) {
            ...
        }
};

关于.net - 如何通过C++/CLI创建.Net扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6012578/

相关文章:

c# - 为什么 0x00 字符使 System.Diagnostics.Debug.WriteLine 不写入新行?

.net - .NET Remoting 中出现 "Tcp channel protocol violation expecting preamble"的原因是什么?

events - 从非托管 C/C++ 函数在 C++/CLI 中触发事件

c# - 为什么 IEnumerable 上没有 ForEach 扩展方法?

c# - 具有动态命名参数的扩展方法

c# - 使用 FileSystemWatcher 监控多个文件夹

c# - 创建一个 "dummy record"来强制数据库服从业务逻辑,是好主意还是愚蠢的主意?

debugging - 如何调试并解决 'DisconnectedContext'崩溃?

string - C++/CLI 将 System::String 转换为 const char*

c# - 为什么带约束的通用扩展方法不被识别为扩展方法?