将类型参数传递给通用自定义类

时间:2012-10-27 04:20:34

标签: vb.net class generics

我看过很多关于这个话题的喋喋不休。虽然这些例子和期望的结果总是非常具体和专业。对此的任何指示都表示赞赏。

自定义类:

Public Class customClass(Of T, S)
[include properties]
[include methods]
End Class

实施课程:

dim [string] as string = string.empty
dim [type] as type = [string].gettype 

dim instance as customClass(of [type], integer) 

另请注意,我已经读过vb.net不允许您将参数传递给它的构造函数。我拒绝接受你不能将类型传递给类并根据该参数的类型生成对象。这个函数在类中唯一的答案是返回一个转换为所需类型的对象列表吗?感谢您的时间。

这个问题是由学术研究推动的。以上是“我想做的事”谢谢。

2 个答案:

答案 0 :(得分:2)

很难看到你正在尝试做什么,但是如果我正在读这个,那你就试图取一个变量并将其用作通用参数。这在.NET中是不可能的 - 当您声明泛型类的变量时,需要编译时类型作为泛型参数,因此它不能是Type类型的变量。

这很重要,原因有两个,其中一个原因是确保满足类型约束。

所以:

Class Foo(Of T)
End Class

Dim x as Type = GetType(String)
Dim y as Foo(Of x)

不起作用 - 您必须这样做:

Dim y as Foo(Of String)

总有反射和表达树,但这更像是一种破解而非解决方案。

答案 1 :(得分:0)

您不能使用动态类型来调用这种类型的声明(Of t,s),但是可以使用接口或继承对某些类型进行“分组”或定界,这也可能非常有用。

Class customClass(Of T As iMyInterface, s As iMyInterface)
End Class

Interface iMyInterface
End Interface

Class MyClass1
    Implements iMyInterface
End Class
Class MyClass2
    Implements iMyInterface
End Class

Dim y As New customClass(Of MyClass1, MyClass2)
相关问题