为什么 C# 编译器说字符串没有 `Contains` 方法

Why does the C# compiler say that string does not have a `Contains` method

为什么 C# 编译器说字符串没有 Contains 方法?

对于此声明

Assert.True(errors.Any(e => e.Message.Contains("hash value",
    StringComparison.OrdinalIgnoreCase)));

编译器说:

'string' does not contain a definition for 'Contains' and the best extension method overload System.Linq.Queryable.Contains<TSource>(System.Linq.IQueryable<TSource>, TSource, System.Collections.Generic.IEqualityComparer<TSource>) has some invalid arguments

对于这个语句,编译器很高兴:

Assert.True(errors.Any(e => e.Message.IndexOf("hash value", 
    StringComparison.OrdinalIgnoreCase) >= 0));

Is the C# compiler getting confused about which Contains to use, or am I?

你是。

正确的方法是IndexOf(),而不是Contains()。只有一个 string.Contains() 重载(如果你可以这样称呼它)和 it doesn't take a StringComparison parameter.