c# - 关于 C# 中的泛型和列表方法 Contains()

标签 c#

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/

相关文章:

C# 显式删除事件处理程序

c# - Dapper:将字符串转换为枚举

c# - 如何使用 ML.NET 预测整数值?

c# - 通过匿名方法订购

c# - 如何处理 LINQ to Entities 仅支持无参数构造函数和初始值设定项

c# - 什么是NullReferenceException,如何解决?

c# - 非空字符串时的触发条件

c# - .NET MVC 的 jQuery getJSON 不工作

c# - 查找 JSON 条目并添加嵌套元素

c# - 返回 json 结果并将 null 转换为空字符串