繁体   English   中英

C# Array.Contains() 编译错误

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

我正在尝试在 C# 中使用 Array.Contains () 方法,并且由于某种原因它无法编译,尽管我相信我使用的是 C# 4.0,并且 ZD7EFA19FBE7D30972FDZ5ADB6 和更高版本应该支持这个。

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

我得到这个错误:

Main.cs(42,15):错误 CS1061:“System.Array”不包含“Contains”的定义,并且找不到接受“System.Array”类型的第一个参数的扩展方法“Contains”(你是缺少 using 指令或程序集引用?)

我正在从命令行编译,没有选项:“csc Main.exe”。

您需要using System.Linq; 在您的程序开始时。

您忘记using System.Linq吗?

顺便说一句,如果您不能使用 LINQ ,还有许多其他选项,例如Array.Exists

如果你不想使用 linq 试试

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

我有同样的问题,我有

using System.Linq

这是因为我试图将 string 与 int进行比较,但不知何故它在说

“System.Array”不包含“包含”的定义

确保您使用的是正确版本的 CSC (csc /?) - 您需要 2010 版本才能编译为 4.0。 您可能还需要添加其他库(/r 选项)以使编译成功。

包含 System.Linq 的答案是正确的,但是这个问题还有另一个原因。 如果 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.
    }
}

我有同样的错误。 由于上面的评论,我意识到该数组不能是二维数组。 虽然我不知道有什么办法可以克服...

暂无
暂无

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

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