首先创建一个Person类.

Code
public class Person
{
string FirstName;
string LastName;
public Person(string first, string last)
{
FirstName = first;
LastName = last;
}
public string FullName
{
get { return FirstName + " " + LastName; }
}
}

Code
class Program
{
static void wl(string s)
{
Console.WriteLine(s);
}
static void w(string s)
{
Console.Write(s);
}
static void br()
{
Console.WriteLine();
}
static void Main(string[] args)
{
#region ArrayDemo
Person scott = new Person("Scott", "Hanselman");
Person bill = new Person("Bill", "Evjen");
Person srini = new Person("Srinivasa", "Sivakumar");
Person[] people ={ bill, scott, srini };
Console.WriteLine("We used foreach.");
foreach (Person p in people)
{
Console.WriteLine(p.FullName);
}
br();
Console.WriteLine("We used a for loop.");
{
for (int i = 0; i < people.Length; i++)
{
Console.WriteLine(people[i].FullName);
}
}
br();
Person scott2 = new Person("Scott", "Hanselman");
int indexOfBill = Array.IndexOf(people, bill);
wl("Bill is at " + indexOfBill);
int indexOfScott = Array.IndexOf(people, scott);
wl("Scott is at " + indexOfScott);
int indexOfScott2 = Array.IndexOf(people, scott2);
wl("Scott2 is at " + indexOfScott2);
#endregion
Console.ReadKey();
}
}
执行结果如下:

虽然这两个对象包含相同的至,但不是同一对象, 如果要获取scott对象的索引,同时把scott2作为要搜索的对象,只需在Person类上提供一个Equals方法, 系统更可以使用该方法建立值相等的对象;
在Person类中重写Equals方法之后的结果如下:

Code
public override bool Equals(object obj)
{
Person other = obj as Person;
return (other.LastName == this.LastName && other.FirstName == this.FirstName);
}
执行结果:

object.Equals方法与 object.ReferenceEquals说明:
object.Equals: 用于对象的等值性比较
object.ReferenceEquals: 用于对象的同一性比较

CodePerson scott = new Person("Scott", "Hanselman");
Person bill = new Person("Bill", "Evjen");
Person srini = new Person("Srinivasa", "Sivakumar");
Person scott2 = new Person("Scott", "Hanselman");
int indexOfBill = Array.IndexOf(people, bill);
wl("Bill is at " + indexOfBill);
int indexOfScott = Array.IndexOf(people, scott);
wl("Scott is at " + indexOfScott);
int indexOfScott2 = Array.IndexOf(people, scott2);
wl("Scott2 is at " + indexOfScott2);
Person scott3 = scott2;
br();
wl("Equals " + object.Equals(scott, scott2).ToString());//对象等值性比较
wl("ReferenceEquals " + object.ReferenceEquals(scott, scott2));//对象同一性比较
#endregion
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架