首先创建一个Person类.


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


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方法之后的结果如下:


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: 用于对象的同一性比较


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