如何在 C++/CLI 中使用 LINQ - 在 VS 2010/.Net 4.0 中 [英] How to use LINQ in C++/CLI - in VS 2010/.Net 4.0

查看:46
本文介绍了如何在 C++/CLI 中使用 LINQ - 在 VS 2010/.Net 4.0 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否有一种方法可以在 C++/CLI 中使用 LINQ.我找到了一篇专注于 VS 2008 的帖子,并且需要为 System::String 类提供一系列解决方法.我在 CodeProject 上看到了一些框架替换,但我想知道是否有一种方法可以直接在 C++/CLI 中使用它.如果可以,谁有好的例子?

Just wondering if there is a way to use LINQ in C++/CLI. I found one post that was focused on VS 2008 and required a bunch of workarounds for the System::String class. I have seen some framework replacements on CodeProject, but I was wondering if there is a way to use it directly in C++/CLI. If you can, anyone have a good example?

推荐答案

您可以使用在 System::Linq 命名空间中定义的 Linq 方法,但您必须跳过几个额外的箍.

You can use the Linq methods that are defined in the System::Linq namespace, but you'll have to jump through a couple extra hoops.

首先,C++/CLI 不支持扩展方法.但是,扩展方法是在System::Linq中定义在各个类上的常规方法,因此您可以直接调用它们.

First, C++/CLI doesn't support extension methods. However, the extension methods are regular methods defined on various classes in System::Linq, so you can call them directly.

List<int>^ list = gcnew List<int>();
int i = Enumerable::FirstOrDefault(list);

其次,C++/CLI 不支持 lambda 表达式.唯一的解决方法是声明一个实际的方法,并将其作为委托传递.

Second, C++/CLI doesn't support lambda expressions. The only workaround is to declare an actual method, and pass that as a delegate.

ref class Foo
{
public:
    static bool GreaterThanZero(int i) { return i > 0; }

    void Bar()
    {
        List<int>^ list = gcnew List<int>();
        int i = Enumerable::FirstOrDefault(list, gcnew Func<int, bool>(&Foo::GreaterThanZero));
    }
}

这篇关于如何在 C++/CLI 中使用 LINQ - 在 VS 2010/.Net 4.0 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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