2014-10-22 80 views
0

有沒有一種方法來產生一種通用的擴展方法,可以採取一種類型並將其轉換爲另一種類型通過將類型的源對象通用/未知輸出類型的構造函數?如何實現擴展方法與通用類型(T),返回新的T2(T)

這是我想賺更多的通用代碼:

<Extension()> 
Public Function ToPublicList(source As List(Of HashTag)) As List(Of WebServiceApiV1.PublicDataClasses.HashtagPublicInfo) 

    Return (From ht In source Select New WebServiceApiV1.PublicDataClasses.HashtagPublicInfo(ht)).ToList() 

End Function 

基本上我想要做的事,以這樣的效果:

<Extension()> 
Public Function ToPublicList(Of T)(source As IEnumerable(Of T), destinationType As Type) As List(Of destinationType) 

    Return (From x As T In source Select New destinationType(x)).ToList() 

End Function 

回答

0

你有沒有使用Convert.ChangeType考慮?

它應該是這樣的:

Return (From x As T In source Select Convert.ChangeType(x, destinationType)).ToList() 

對於這項工作,destinationType必須實現的接口IConvertible