.Net 相等性的测试题目,看你基础牢不牢
2009-09-04 20:01 鹤冲天 阅读(3740) 评论(11) 编辑 收藏 举报有这么一个简单类People:
class People
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Id: {0}; Name: {1}", Id, Name);
}
}
{
public int Id { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Id: {0}; Name: {1}", Id, Name);
}
}
请看以下代码,给出b0~b6的值(b6的相关代码不熟悉的话,可以只给出b0~b5的值):
private static void Test()
{
People[] ps0 = new People[]{
new People{ Id=1, Name = "aaa"},
new People{ Id=2, Name = "bbb"},
new People{ Id=3, Name = "ccc"}
};
List<People> ps1 = new List<People>(ps0);
Collection<People> ps2 = new Collection<People>(ps1);
IEnumerable<People> ps3 = YeildRet(ps0);
Dictionary<People, string> dict = ps0.ToDictionary(p=>p, p=>p.Name);
People p0 = new People { Id = 1, Name = "aaa" };
//
bool b0 = p0 == ps0[0];
bool b1 = p0.Equals(ps0[0]);
//
bool b2 = ps0.Contains(p0);
bool b3 = ps1.Contains(p0);
bool b4 = ps2.Contains(p0);
bool b5 = ps3.Contains(p0);
//
bool b6 = dict.ContainsKey(p0);
}
private static IEnumerable<People> YeildRet(People[] peoples)
{
yield return peoples[0];
yield return peoples[1];
yield return peoples[2];
}
{
People[] ps0 = new People[]{
new People{ Id=1, Name = "aaa"},
new People{ Id=2, Name = "bbb"},
new People{ Id=3, Name = "ccc"}
};
List<People> ps1 = new List<People>(ps0);
Collection<People> ps2 = new Collection<People>(ps1);
IEnumerable<People> ps3 = YeildRet(ps0);
Dictionary<People, string> dict = ps0.ToDictionary(p=>p, p=>p.Name);
People p0 = new People { Id = 1, Name = "aaa" };
//
bool b0 = p0 == ps0[0];
bool b1 = p0.Equals(ps0[0]);
//
bool b2 = ps0.Contains(p0);
bool b3 = ps1.Contains(p0);
bool b4 = ps2.Contains(p0);
bool b5 = ps3.Contains(p0);
//
bool b6 = dict.ContainsKey(p0);
}
private static IEnumerable<People> YeildRet(People[] peoples)
{
yield return peoples[0];
yield return peoples[1];
yield return peoples[2];
}
下面会把People类逐步改进,同样请给出每个版本的b0~b6的值,一个版本一个版本做,做完一个版本才能展开下一个版本。不要作弊奥!
People版本二
再改进,
People版本三
再改进
People版本四
再改进:
People版本五
说明:代码仅供测试用,没有进行null值处理。
-------------------
思想火花,照亮世界