在转换中使用了TInput和TOutput泛型类型.TInput是委托方法的参数.TOutput是返回类型.
我们现在把Racer类型转换为Person类型.
使用List<T>de ConvertAll()方法,可以吧任意类型的集合转换为另一种类型.OnvertAll()方法使用Converter委托.
public sealed delegate TOutput Converter<TInput,TOutput>(TInput from);
在转换中使用了TInput和TOutput泛型类型.TInput是委托方法的参数.TOutput是返回类型.
我们现在把Racer类型转换为Person类型.
public class Person
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
private string firstname;
private string lastname;
public Person(string firstname,string lastname)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.firstname=firstname;
this.lastname = lastname;
}
public override string ToString()
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return firstname+" "+lastname;
}
}
//在调用racer.ConvertAll<Person>()方法时转换
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
List<Person> persons = racer.ConvertAll<Person>(delegate(Racer r)
{
int ixSeparator=r.Name.LastIndexOf(' ')+1;
string lastname = r.Name.Substring(ixSeparator,r.Name.Length-ixSeparator);
string firstname=r.Name.Substring(0,ixSeparator-1);
return new Person(firstname,lastname);
});
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
persons.ForEach(delegate(Person p)
{ Console.WriteLine(p); });
这样就把姓名分离,大家看出来其实委托里面的其实就是分离的方法,然后在New一个新的实例赋给泛型,他为什么要用委托呢?如果我们用racer.ForEach(),然后根据条件吧姓名分开,效率书不是一样呢.