[英]How do I make the method/s generic which returns different types, but accepts the same type of instance?
[英]How to make a function which returns Type <T>
C#.NET 4.0
我创建了一个将ArrayList转换为List的函数
List<MatchBowlDetails> lstBowling = ConvertArrayListToList(BowlingTeamScore).Cast<MatchBowlDetails>().ToList();
public static List<Object> ConvertArrayListToList(CollectionClass paramcollection)
{
//Function use:
//This function takes array List and return List<Type>
//TODO
return null;
}
如您所见,我创建了一个将ArrayList
转换为List<T>
的函数。
这里BowlingTeamScore
是MatchBowlDetails
类的集合,并且继承自CollectionClass
,后者使ArrayList
类型成为集合。
现在,这里,因为这函数返回List<Object>
对象的类型和欲返回List<T>
的类型T
,其中T
是paramCollection.GetType();
因此,新的用户代码将为:
List<MatchBallDetails> lstBowling = ConvertArrayListToList<BowlingTeamScore); // here no need to type cast back..
请提出如何做到这一点。
你的意思是这样吗?
public static List<T> ConvertArrayListToList<T>(CollectionClass paramcollection)
{
return paramcollection.Cast<T>().ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.