开发者

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.

if (! args.Contains ("-m"))
    Console.WriteLine ("You must provide a me开发者_运维百科ssage 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?)

I am compiling from the command line, with no options: "csc Main.exe".


You need to add using System.Linq; at the beginning of your program.


Did you forget using System.Linq?

By the way, if you can't use LINQ there are many other options such as Array.Exists.


If you dont' want to use linq try

((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

'System.Array' does not contain a definition for 'Contains'


The answers saying to include System.Linq are spot on, however there is one other cause of this problem. If the type of the argument for .Contains() does not match the type of the array, you will get this error.

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.
    }
}


Make sure you are using correct version of CSC (csc /?) - you need 2010 version to compile for 4.0. You also may need to add additional libraries (/r option) for compile to succeed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜