@sharif
2018-02-26T11:59:23.000000Z
字数 2523
阅读 1021
习题
集合CollectionBase
键控集合DictionaryBase
迭代器
IEnumerable 与 IEnumerator
迭代一个类,可以使用方法GetEnumerator(),返回类型IEnumerator;
迭代一个类成员,可以使用方法GetEnumerable(),返回类型IEnumerable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise
{
class Program
{
static void Main(string[] args)
{
Person p1 = new Person("1", 10);
Person p2 = new Person("2", 89);
Person p3 = new Person("3", 58);
Person p4 = new Person("4", 49);
People people = new People();
people.Add(p1);
people.Add(p2);
people.Add(p3);
people.Add(p4);
foreach (int i in people.GetAges())
{
Console.WriteLine($"i:{i}");
}
Console.ReadKey();
}
}
public class Person
{
private string name;
private int age;
public string Name { get => name; set => name = value; }
public int Age { get => age; set => age = value; }
public Person(string name, int age)
{
this.age = age;
this.name = name;
}
public Person()
{
}
public static bool operator >(Person per1, Person per2) => per1.age > per2.age;
public static bool operator <(Person per1, Person per2) => per1.age > per2.age;
public static bool operator >=(Person per1, Person per2) => !(per1 < per2);
public static bool operator <=(Person per1, Person per2) => !(per1 > per2);
}
public class People : DictionaryBase, ICloneable
{
public void Add(Person newPerson)
{
Dictionary.Add(newPerson.Name, newPerson);
}
public void Remove(string personName)
{
Dictionary.Remove(personName);
}
public Person this[string personName]
{
get { return (Person)Dictionary[personName]; }
set { Dictionary[personName] = value; }
}
public Person[] GetOldest()
{
Person oldestPerson = null;
People oldestPeople = new People();
Person currentPerson;
foreach (DictionaryEntry p in Dictionary)
{
currentPerson = p.Value as Person;
if (oldestPerson == null)
{
oldestPerson = currentPerson;
}
else
{
if (currentPerson > oldestPerson)
{
oldestPeople.Clear();
oldestPeople.Add(currentPerson);
}
else
{
if (currentPerson >= oldestPerson)//没有定义‘==’运算哦
{
oldestPeople.Add(currentPerson);
}
}
}
}
Person[] returnPersons = new Person[Dictionary.Count];
for (int i = 0; i < Dictionary.Count; i++)
{
returnPersons[i] = (Person)Dictionary[i];
}
Dictionary.CopyTo(returnPersons, 0);
return returnPersons;
}
public object Clone()
{
//People newPeople = new People();
//foreach (Person per in List)
//{
// newPeople.List.Add(new Person(per.Name, per.Age));
//}
//return (object)newPeople;
People clonePeople = new People();
Person currentPerson, newPerson;
foreach (DictionaryEntry p in Dictionary)
{
currentPerson = p.Value as Person;
newPerson = new Person();
newPerson.Name = currentPerson.Name;
newPerson.Age = currentPerson.Age;
clonePeople.Add(newPerson);
}
return clonePeople;
}
public IEnumerable GetAges()
{
foreach (Object per in Dictionary)
{
yield return (per as Person).Age;
}
}
}
}