• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
①只螃蟹?条腿™...
.NET世界是如此精彩,而我们要做的就是:Thinking More..
博客园    首页    新随笔       管理    订阅  订阅
用泛型List实现集合类及排序功能
1)首先定义一个Person类
class Person
{
    
private int age;

    
public int Age
    
{
        
get { return age; }
        
set { age = value; }
    }


    
public Person(int age)
    
{
        
this.age = age;
    }

}

2)再定义一个PersonList集合类,只要继承List<Person>就好了

class PersonList : List<Person>
{
    
// 根据Comparison定义的签名,定义排序方法
    public static int PersonSort(Person x, Person y)
    
{
        
if (x.Age > y.Age)
        
{
            
return -1;
        }

        
if (x.Age < y.Age)
        
{
            
return 1;
        }

        
return 0;
    }

}

3)入口函数调用
static void Main(string[] args)
{
    PersonList pList 
= new PersonList();
    pList.Add(
new Person(17));
    pList.Add(
new Person(21));
    pList.Add(
new Person(19));
    pList.Add(
new Person(12));

    Console.WriteLine(
"默认顺序:");
    
foreach (Person p in pList)
    
{
        Console.WriteLine(p.Age);
    }


    
// 定义 强类型委托
    Comparison<Person> sorter = new Comparison<Person>(PersonList.PersonSort);
    pList.Sort(sorter);

    Console.WriteLine(
"自定义排序:");
    
foreach (Person p in pList)
    
{
        Console.WriteLine(p.Age);
    }


    Console.ReadKey();
}

Plus:Comparsion<T>这个委托类型用于排序,其签名是
int method( T objectA, T objectB )

小结:

用泛型的方式来定义一个集合类及一些方法,的确比继承自一个CollectionBase来的更方便,其中不用再去手动地写Add()、Remove()之类的方法了。而如果希望集合类的Add()方法使用内部访问修饰符,则还是推荐使用CollectionBase。
posted on 2008-05-14 11:04  A.feng..  阅读(1066)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3