我想创建一个 VB.NET 通用工厂方法来创建类的实例(作为本地开发的控制反转容器)。如果我将接口(interface) IDoSomething 作为通用参数传递,我想返回 DoSomething 的实例(实现 IDoSomething)。我无法弄清楚 if 语句的语法。我想写这样的东西:
Public Function Build(Of T) as T
If T Is IDoSomething then
Return New DoSomething()
ElseIf T Is IAndSoOn Then
Return New AndSoOn()
Else
Throw New WhatWereYouThinkingException("Bad")
End If
End Sub
但是这段代码无法编译。
最佳答案
Public Function Build(Of T) As T
Dim foo As Type = GetType(T)
If foo Is GetType(IDoSomething) Then
Return New DoSomething()
...
End If
End Function
关于.net - 如何根据传递给 VB.NET 泛型方法的类型执行条件逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/149484/