代码如下:
using System.Collections;
namespace ConsoleApplication_test
{
public class Member
{
private string _name;
public Member() { }
public Member(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public override bool Equals(object obj)
{
Member member = (Member)obj;
return (_name == member.Name) ? true : false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator ==(Member member1, Member member2)
{
return member1.Equals(member2) ? true : false;
}
public static bool operator !=(Member member1, Member member2)
{
return !(member1 == member2);
}
}
public class Members : CollectionBase
{
public Member this[int index]
{
get { return (Member)List[index]; }
set { List[index] = value; }
}
public int IndexOf(Member member)
{
return this.List.IndexOf(member);
}
public void Add(Member member)
{
this.List.Add(member);
}
public void Remove(Member member)
{
if (this.IndexOf(member) != -1)
List.Remove(member);
}
}
class Program
{
static void Main_test()
{
Members members = new Members();
// insert
members.Add(new Member("Clare"));
members.Add(new Member("Jessie"));
members.Add(new Member("Jingyi"));
// modify
int index = members.IndexOf(new Member("Clare"));
if (index != -1)
{
members[index] = new Member("Jessie");
}
// delete
members.Remove(new Member("Clare"));
// search
if (index != -1) members.RemoveAt(index);
foreach (Member member in members)
{
Console.WriteLine(member.Name);
}
Console.ReadLine();
}
}
}
2.0下面可以优化,精简
using System.Collections.ObjectModel;
namespace ConsoleApplication_test
{
public class Members_test : Collection<Member>
{
}
class program1
{
static void Main(string[] args)
{
Members members = new Members();
// insert
members.Add(new Member("Clare"));
members.Add(new Member("Jessie"));
members.Add(new Member("Jingyi"));
// modify
int index = members.IndexOf(new Member("Clare"));
if (index != -1)
{
members[index] = new Member("Jessie");
}
// delete
members.Remove(new Member("Clare"));
// search
if (index != -1) members.RemoveAt(index);
foreach (Member member in members)
{
Console.WriteLine(member.Name);
}
Console.ReadLine();
}
}
}
Conclusion
泛型最基本的應用,也是最原始的應用,就是在container,若用OO,只能用多型(多態)的技術,讓container放Object type,進Container須轉型成Object,出Container需再轉回各type,若用泛型,就可直接將各type放進container,不需轉型,不只速度提升,且code也非常的精簡。