繁体   English   中英

C#(.NET 2.0)中的Python'in'运算符等效

[英]Python 'in' operator equivalent in C# (.NET 2.0)

我喜欢python in-operator ,我想编写它并在c#项目中使用它。 我只能访问.NET Framework 2.0 我正在使用下面的代码,但我不理解编译错误。

using System;
using System.Collections.Generic;
using System.Text;

public static bool In<T>(this T item, IEnumerable<T> sequence) {
    if (sequence == null)
        throw new ArgumentNullException("sequence");

    return sequence.Contains(item);
}

我也有对System的引用,但是出现以下编译错误:

'System.Collections.Generic.IEnumerable<T>' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Collections.Generic.IEnumerable<T>' could be found
(are you missing a using directive or an assembly reference?)

我不明白我可能会缺少哪些参考!

编辑:

似乎.NET Framework 2.0中没有Linq。 因此,我下载并使用了以下软件包: http : //www.albahari.com/nutshell/linqbridge.aspx,它包含一个namespace System.Linq ,可以解决编译错误。

我想用以下代码进行测试:

char[] x = { 'a', 'b', 'c' };
if('a'.In(x))
{
    ;   
}

但是我得到了令人困惑的错误:

'char' does not contain a definition for 'In' and no extension method 'In' accepting a first argument of type 'char' could be found
(are you missing a using directive or an assembly reference?)

编辑:一个干净的内置解决了问题。

Contains静态方法在System.Linq内部定义。

如果using System.Linq;添加该行using System.Linq; 在文件顶部,应编译代码。

顺便说一句,Contains方法是否与Python的“ in”运算符相同? 通过创建自定义方法,您实际上并不会获得太多收益,除了您可以键入更少的字符/可以反转操作数之外。

如果您使用的是.NET 2.0,则可以代替本文使用Linq来适应本SO帖子中的一种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM