编译错误 · error CS1061

"X"未包含"Y"的定义

你向一个值索要它的成员——方法、属性、字段——而它的类型根本没有这个成员。和 CS0103(不认识的变量)不同:这里变量没问题,是点号后面的部分出了问题。

亲眼看它发生

string s = "hello";
Console.WriteLine(s.Lenth);   // string 有 Length——不是 Lenth
string s = "hello";
Console.WriteLine(s.Length);  // 大写 L,一个字母不差

成因一:拼写或大小写错(最常见)

错误消息会指明它查找的确切类型——读它。'string' 未包含 'Lenth' 的定义说明编译器知道 s 是字符串,并且查遍了字符串能做的一切。拼错是唯一的问题:

你写的C# 要的
s.Lenths.Length
s.toUpper()s.ToUpper() — PascalCase 大驼峰
list.countlist.Count
arr.Sizearr.Length — 数组用 Length,不是 Size

成因二:自己的成员拼错

class Dog
{
    public string Name;

    public void Bark()
    {
        Console.WriteLine(Name + " says woof");
    }
}

Dog d = new Dog { Name = "Rex" };
d.Barkk();   // 少了一个 k
class Dog
{
    public string Name;

    public void Bark()
    {
        Console.WriteLine(Name + " says woof");
    }
}

Dog d = new Dog { Name = "Rex" };
d.Bark();

成因三:成员存在——但在别的类型上

你把方法调到了错误的对象身上。经典:在数组上调 List 的方法(它们长得像,但不是一回事):

int[] arr = { 1, 2, 3 };
arr.Add(4);        // error CS1061: 数组是定长的——没有 Add
                   // 想添加?用 List<int>:

var list = new List<int> { 1, 2, 3 };
list.Add(4);       // ✓ 没问题

成因四:把不是方法的东西当方法调用

属性像字段一样读,不像方法一样调。给属性加 () 就会踩中这个错(Visual Studio 会说 CS1955——"不可调用的成员不能像方法一样使用"):

var list = new List();
list.Add(1);
Console.WriteLine(list.Count());   // Count 是属性——不能加 ()
var list = new List();
list.Add(1);
Console.WriteLine(list.Count);    // 属性:没有括号

经验法则:做某事的是方法(());是某物的是属性(没有 ())。list.Add(x) 是动作;list.Count 只是"是"。

常见问答

C# 里的 CS1061 是什么意思?

点号后的成员在该类型上不存在。常见原因:拼写错(s.Lenth → s.Length)、大小写错(s.toUpper() → s.ToUpper())、把属性当方法调用(list.Count() → list.Count)、或在数组上调 List 的方法。

C# 里 Count 要不要加括号?

List<T>.Count 是属性,不加括号;数组用 .Length,同样不加。方法才要括号——list.Add(x)、s.ToUpper()。

排查清单