VB.NET:如何处理变量类型(参数和返回值)?

时间:2011-05-25 18:41:15

标签: .net vb.net

是否可以替换这两个功能

Function f1 (s As String) As class1()
  Dim a() As String = Split(s)
  Dim b(UBound(a)) As class1
  For i As Integer = 0 To UBound(a)
    b(i) = New class1(a(i))
  Next
  f1 = b
End Function

Function f2 (s As String) As class2()
  Dim a() As String = Split(s)
  Dim b(UBound(a)) As class2
  For i As Integer = 0 To UBound(a)
    b(i) = New class2(a(i))
  Next
  f2 = b
End Function

使用类似

的泛型函数
Function fGeneric (s As String,T As Type) As T()
  Dim a() As String = Split(s)
  Dim b(UBound(a)) As T
  For i As Integer = 0 To UBound(a)
    b(i) = New T(a(i))
  Next
  fGeneric = b
End Function

Class class1
  Private _Name As String
  Public ReadOnly Property Name As String
    Get
      Name = _Name
    End Get
  End Property
  Sub New(s As String)
    _Name = s
  End Sub
End Class

Function fGeneric(Of T) (s As String) As IEnumerable(Of T)
  Dim a() As String = Split(s)
  Dim b(UBound(a)) As T
  For i As Integer = 0 To UBound(a)
    b(i) = GetType(T).InvokeMember( _
      Nothing, _
      BindingFlags.DeclaredOnly Or _
      BindingFlags.Public Or _
      BindingFlags.NonPublic Or _
      BindingFlags.Instance Or _
      BindingFlags.CreateInstance, _
      Nothing, _
      Nothing, _
      New Object(){a(i)} _
    )
  Next
  fGeneric = b
End Function

Response.Write(fGeneric(Of class1)("a b c")(1).Name)输出b

3 个答案:

答案 0 :(得分:3)

Function fGeneric(Of T) (ByVal s As String, ByVal createT As Func(Of String, T)) As IEnumerable(Of T)
  Return Split(s).Select(Function(a) createT(a))
End Function

像这样称呼它

fGeneric(Of class1)("some, string, value", Function(a) Return New class1(a))

答案 1 :(得分:2)

@Joel指出这可以用linq优雅地解决,但为了接近@ ic3b3rg的问题,语法将是:

Function fGeneric(Of T As New) (s As String, createT As Func(Of String, T)) As T()
  Dim a() As String = Split(s)
  Dim b(UBound(a)) As T
  For i As Integer = 0 To UBound(a)
    b(i) = createT(a(i))
  Next
  fGeneric = b
End Function

fGeneric(Of class1)("some, string, value", Function(a) Return New class1(a))

修改

仔细观察我认为这不会起作用,因为我们从未说过T可以用String构建。我们只是说可以使用T创建new。我不知道如何解决它...欢迎任何建议(随时编辑)。

答案 2 :(得分:0)

看看Reflections。我认为它可以帮助您获得与您的示例更密切相关的结果。