简体   繁体   English

C# Array.Contains() 编译错误

[英]C# Array.Contains () compilation error

I'm trying to use the Array.Contains () method in C#, and for some reason it's failing to compile, eve though I believe that I'm using C# 4.0, and C# should support this in 3.0 and later.我正在尝试在 C# 中使用 Array.Contains () 方法,并且由于某种原因它无法编译,尽管我相信我使用的是 C# 4.0,并且 ZD7EFA19FBE7D30972FDZ5ADB6 和更高版本应该支持这个。

if (! args.Contains ("-m"))
    Console.WriteLine ("You must provide a message for this commit.");

And I get this error:我得到这个错误:

Main.cs(42,15): error CS1061: 'System.Array' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) Main.cs(42,15):错误 CS1061:“System.Array”不包含“Contains”的定义,并且找不到接受“System.Array”类型的第一个参数的扩展方法“Contains”(你是缺少 using 指令或程序集引用?)

I am compiling from the command line, with no options: "csc Main.exe".我正在从命令行编译,没有选项:“csc Main.exe”。

You need to add using System.Linq;您需要using System.Linq; at the beginning of your program.在您的程序开始时。

Did you forget using System.Linq ?您忘记using System.Linq吗?

By the way, if you can't use LINQ there are many other options such as Array.Exists .顺便说一句,如果您不能使用 LINQ ,还有许多其他选项,例如Array.Exists

If you dont' want to use linq try如果你不想使用 linq 试试

((IList<string>)args).Contains("-m")

I had the same issue and I had我有同样的问题,我有

using System.Linq

It was because I was trying to compare string to int , but somehow it was saying这是因为我试图将 string 与 int进行比较,但不知何故它在说

'System.Array' does not contain a definition for 'Contains' “System.Array”不包含“包含”的定义

Make sure you are using correct version of CSC (csc /?) - you need 2010 version to compile for 4.0.确保您使用的是正确版本的 CSC (csc /?) - 您需要 2010 版本才能编译为 4.0。 You also may need to add additional libraries (/r option) for compile to succeed.您可能还需要添加其他库(/r 选项)以使编译成功。

The answers saying to include System.Linq are spot on, however there is one other cause of this problem.包含 System.Linq 的答案是正确的,但是这个问题还有另一个原因。 If the type of the argument for.Contains() does not match the type of the array, you will get this error.如果 for.Contains() 的参数类型与数组的类型不匹配,则会出现此错误。

public class Product
{
    public long ProductID {get;set;}
}

public IEnumerable<Product> GetProductsByID(int[] prodIDs)
{
    using (var context = new MyDatabaseContext())
    {
        return context.Products.Where(product => prodIDs.Contains(product.ProductID)); // ['System.Array' does not contain a definition for 'Contains'] error because product.ProductID is long and prodIDs is an array of ints.
    }
}

I had the same error.我有同样的错误。 I realised, thanks to a comment above, that the array can't be a 2D array.由于上面的评论,我意识到该数组不能是二维数组。 I don't know a way of getting past that though...虽然我不知道有什么办法可以克服...

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

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