[英]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.