我可以在类属性中使用泛型吗? [英] Can I have generics in a Class Property?

查看:523
本文介绍了我可以在类属性中使用泛型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义为

Public MustInherit Class Entity(Of T As Entity(Of T))

以及从中派生的各种类.我想让另一个类接受所有派生对象作为属性,但是我似乎无法找到可行的语法.如果它是sub的参数,我可以说

And various classes derived from it. I would like to have another class accept all of the derived objects as a property, but I cannot seeem to find a workable syntax. If it were a parameter of a sub, I could say

Public Sub Foo(T As Entity(Of T))(TheEntity As T)

我似乎无法将其用于物业:

I can't seem to get that to work for a property:

Public Property E(Of Entity(Of T))() As Entity(Of T)

给我不能在此声明中指定类型参数"

Gives me "Type parameters cannot be specified on this declaration"

Public Property E() As Entity2008(Of T)

给我类型参数T不会继承或实现约束类型..."

Gives me "Type Parameter T does not inherit from or implement the constraint type ..."

有没有一种可接受的方法来执行此操作,或者我是否坚持使用Set Sub和Get Function?

Is there an acceptable way to do this or am I stuck with using a Set Sub and a Get Function?

推荐答案

要声明该属性,编译器需要在编译时知道类型是什么. (这是方法可以做到的,属性不能做到.)

To declare the property, the compiler needs to know at compile time what the type would be. (This is something methods can do, that properties cannot).

请考虑将数据IEnumerable(Of yourtype)绑定到DataGridView的情况,这将枚举所有属性并为每个属性创建一列.当它到达假设的通用属性时,它没有任何信息可替代哪种类型.

Consider the case where you were data binding an IEnumerable(Of yourtype) to a DataGridView, which will enumerate all the properties and make a column for each. When it hits the hypothetical generic property, it has no information for which type to substitute.

请考虑以下情况:您有一个类的实例,并设置了E属性-可以设置具有两个不同签名的两个属性,也许一个为:

Consider the case where you've got an instance of your class, and you set your E property -- it would be possible to set two properties with two different signatures, maybe one as:

foo.E(Of Entity(Of Byte)) = New Entity(Of Byte)

另一个是:

foo.E(Of Entity(Of Guid)) = New Entity(Of Guid)

那么,应该设置不同的属性吗?设置一个签名是否应该设置另一个签名的值?显然,在上述情况下,类型不能相互转换.

So, should they set different properties? Should setting one signature set the value for the other? Obviously in the case above, the types are not convertible to each other.

没有什么可以阻止您这样做:

There is nothing to stop you from doing:

Public MustInherit Class Entity(Of T As Entity(Of T))
    Public Property E() As Entity(Of T)
        Get
            Throw New NotImplementedException()
        End Get
        Set
            Throw New NotImplementedException()
        End Set
    End Property
End Class

在这种情况下,实体只能具有相同的类型,并且其E属性必须与自身具有相同的类型(除非您装饰

And in this case, you could only ever have the same type for the Entity and its E property would have to be of the same type as itself (Unless you decorate for variance)

这篇关于我可以在类属性中使用泛型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆