List<Employee> staff = new List<Employee>();
Employee newHire = new Employee("John Smith", "1101");
staff.Add(newHire);
if (staff.Contains(newHire))
Console.WriteLine("Yes the list contains the item we just added\n\t{0}", newHire.ToString());
newHire = new Employee("John Smith", "1101");
if (staff.Contains(newHire))
Console.WriteLine("The list also contains this Employee");
else
Console.WriteLine("Nope, can't find John Smith");
代码是用来解释Contains()
如何使用的,但是我对
实例 newHire。好像我们创建了两次这个实例,我不知道它们之间有什么区别。
我是 C# 的新手,英语不是我的母语。
最佳答案
这是发生了什么:
首先你创建一个空列表和一个Employee
类型的对象
List<Employee> staff = new List<Employee>();
Employee newHire = new Employee("John Smith", "1101");
现在在内存中我们有
newHire --> points to address 0x00000001 // example of an address for the variable content
然后我们把它放到列表中
staff.Add(newHire);
内存
newHire --> points to address 0x00000001
staff(0) --> points to address 0x00000001
下面的代码可以工作,因为两个地址是一样的
if (staff.Contains(newHire))
Console.WriteLine("Yes the list contains the item we just added\n\t{0}", newHire.ToString());
现在是小技巧
newHire = new Employee("John Smith", "1101");
这将创建一个类型为 Employee 的新对象,其信息与第一个对象完全相同。 但是是新的
所以现在在内存中我们有
newHire --> points to address 0x00000004 // A new address has been assigned to the new object
staff(0) --> points to address 0x00000001
下面的意思是“staff 是否包含存储在地址 0x00000004 的对象?”
if (staff.Contains(newHire))
Console.WriteLine("The list also contains this Employee");
else
Console.WriteLine("Nope, can't find John Smith");
当然,答案是否定的,列表仍然保留对 0x00000001 处对象的引用
关于c# - 关于 C# 中的泛型和列表方法 Contains(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52851319/