【问题标题】:Python 'in' operator equivalent in C# (.NET 2.0)C# (.NET 2.0) 中等效的 Python 'in' 运算符
【发布时间】:2014-09-09 06:23:12
【问题描述】:

我喜欢 pythons 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 框架 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?)

编辑: 干净的构建解决了这些问题。

【问题讨论】:

  • Linq 在 .NET Framework 2.0 中不可用,因此您将无法使用“包含”

标签: c# python extension-methods operator-keyword


【解决方案1】:

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

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

顺便说一句,Contains 方法不与 Python 的“in”运算符相同吗?创建自定义方法并没有真正获得太多收益,只是您可以输入更少的字符/可以反转操作数。

如果您使用的是 .NET 2.0,则可以采用 this SO post 中的一种方法来代替使用 Linq。

【讨论】:

  • 我们可以在c#中使用“include”而不是“using”吗?
  • @Rain -- 哎呀!你是对的,它应该是“使用”。我搞混了另一种语言。
  • @Michael0x2a,抱歉,请参阅更新的问题,我错过了提到房间里的巨象。
  • System.Linq 不在 .Net v2.0 中,我想。它从 v3.5 开始。
  • @NonStatic - 是的,这个问题最初没有提到。我现在正在寻找另一种方法。
猜你喜欢
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多