如何实现泛型类型(T)的返回新T2(T)的扩展方法

时间:2014-10-22 10:58:31

标签: .net vb.net generics extension-methods ienumerable

有没有办法通过将类型的源对象传递给泛型/未知输出类型的构造函数来生成可以采用一种类型并将其转换为另一种类型的通用扩展方法?

这里是我想要更通用的代码:

<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

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用Convert.ChangeType

看起来像这样:

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

为此,destinationType必须实现接口IConvertible