我不确定这是否可行.
我有许多实现接口IBar的不同类,并且具有带有几个值的构造函数.而不是创建一堆几乎相同的方法,是否有可能有一个通用的方法,将创建适当的构造函数?
private function GetFoo(Of T)(byval p1, byval p2) as List(Of IBar)
dim list as new List(Of IBar)
dim foo as T
' a loop here for different values of x
foo = new T(x,p1)
list.Add(foo)
' end of loop
return list
end function
Run Code Online (Sandbox Code Playgroud)
我明白了:
'New' cannot be used on a type parameter that does not have a 'New' constraint.
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 12
遗憾的是 - .NET泛型只允许您将泛型类型约束为具有无参数构造函数,然后可以使用它来调用New T()...您无法指定一组特定的参数.
如果您不介意使您的类型变为可变,您可以创建一个包含带有相关参数的方法的接口,使所有类型实现接口,然后约束类型以实现该方法并具有无参数构造函数,但它是不理想.
另一种选择是在一个合适的通过Func这需要x和p1并返回一个新的T各一次.这肯定会很容易从C#中使用-不是很那么容易在VB IIRC,但值得考虑的还是.
扩展Jon Skeet的答案,以下是使用Func参数的可能解决方案:
Private Function GetFoo(Of T As IBar)(ByVal p1 As Object, ByVal p2 As Object, ctor As Func(Of Integer, Object, T)) As List(Of IBar)
Dim list As New List(Of IBar)
Dim foo As T
For x = 1 To 10
foo = ctor(x, p1)
list.Add(foo)
Next
Return list
End Function
Run Code Online (Sandbox Code Playgroud)
用法将类似于
GetFoo(1, 2, Function(i, o) New BarImpl(i, o))
Run Code Online (Sandbox Code Playgroud)