C#集合與列表(一) -- 對象的統一性和對象的等值性
首先創建一個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
浙公網安備 33010602011771號