如何创建由C ++ / CLI的.Net扩展方法? [英] How can I create .Net extension methods by C++/CLI?

查看:147
本文介绍了如何创建由C ++ / CLI的.Net扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 ?

推荐答案

您只需要装饰方法和含有类<一href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx">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) {
            ...
        }
};

这篇关于如何创建由C ++ / CLI的.Net扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆