具体参考实例:https://mp.csdn.net/console/editor/html/105405707
一、泛型实例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person p1 = new Person("xiaoming", 20);
Person p2 = new Person("xiaohong", 22);
Person p3 = new Person("xiaowang", 21);
List<Person> persons = new List<Person>();
persons.Add(p1);
persons.Add(p2);
persons.Add(p3);
Console.Write(persons[1].Name);
}
}
}
namespace ConsoleApplication1
{
class Person
{
private string _Name;
private int _Age;
//创建对象
public Person(string Name, int Age)
{
this._Name = Name;
this._Age = Age;
}
//姓名
public string Name
{
get { return _Name; }
}
//年龄
public int Age
{
get { return _Age;}
}
}
}
二、自定义对象类型默认排序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person p1 = new Person("xiaoming", 20);
Person p2 = new Person("xiaohong", 22);
Person p3 = new Person("xiaowang", 21);
List<Person> persons = new List<Person>();
persons.Add(p1);
persons.Add(p2);
persons.Add(p3);
persons.Sort();
foreach(Person p in persons)
{
Console.WriteLine("{0}, {1}",p.Name, p.Age); //WriteLine自动换行打印
}
}
}
}
namespace ConsoleApplication1
{
class Person : IComparable<Person>
{
private string _Name;
private int _Age;
//创建对象
public Person(string Name, int Age)
{
this._Name = Name;
this._Age = Age;
}
//姓名
public string Name
{
get { return _Name; }
}
//年龄
public int Age
{
get { return _Age;}
}
//对象本身不是一个具体的值,在排序逻辑上显然要选择对象的一个属性进行排序。
public int CompareTo(Person other)
{
//return this.Age.CompareTo(other.Age); //升序
return other.Age.CompareTo(this.Age); //降序
}
}
}