1.如果为实体类型
//实体类型
var stu = new Student() {StudentId = 1, StudentName = "aaaaa"};
if (list.Contains(stu))
{
Console.WriteLine("实体类型包含");
}必须重写Equals方法:
public partial class Student:IEquatable<Student>
{
public bool Equals(Student other)
{
if (this.StudentId==other.StudentId && this.StudentName==other.StudentName)
{
return true;
}
else
{
return false;
}
}
}2.引用类型
//List引用类型
var list2 = new List<string>();
list2.Add("111");
list2.Add("222");
list2.Add("333");
if (list2.Contains("222"))
{
Console.WriteLine("引用类型包含");
}3.值类型
//值类型
var list3 = new List<int>();
list3.Add(111);
list3.Add(222);
list3.Add(333);
if (list3.Contains(222))
{
Console.WriteLine("值类型包含");
}

本文通过示例代码介绍了C#中值类型、引用类型及实体类型的使用区别,重点展示了如何针对实体类型重写Equals方法以实现正确的对象比较,并对不同类型在List中的Contains方法行为进行了说明。
1580

被折叠的 条评论
为什么被折叠?



