[英]How to declare property as generic type constrained to classes that inherits a base class?
Update1: It was kind of a duplicate before this update, but I think now it's specific enough and the duplicate doesn't answer this edited question at all. Update1:在此更新之前它有点重复,但我认为现在它已经足够具体了,副本根本不回答这个编辑过的问题。 Ok, so I found out that I must use a Generic Class with constraints.
好的,所以我发现我必须使用带有约束的通用类。 The problem still remains about how can I constrain only to classes derived from a class.
问题仍然存在,我如何只限制从类派生的类。
Practically, I want to be able to declare some kind of abstract property, with a type declared in a derived class, but limited only to derived types declared in the original class. 实际上,我希望能够声明某种抽象属性,其类型在派生类中声明,但仅限于在原始类中声明的派生类型。 Let's take this example:
我们来看这个例子:
Public Class ObjectBase
End Class
Public Class Derived1Class
inherits ObjectClass
Public Property1 as String
End Class
Public class Derived2Class
inherits ObjectClass
Public Property2 as string
End Class
Public Class SomeOtherClass(Of T as {OnlyClassesWhichInherits(ObjectBase)})
Public Property SomeProperty as T
End Class
Public Class SomeOtherDerivedClass
inherits SomeOtherClass
Sub New()
SomeProperty = New Derived1Class
SomeProperty.Property1:="this should be valid"
End Sub
End Class
The only way I know so that this can be accomplished is by declaring SomeProperty as Object(Update1:now I now this feature is named generic classes). 我知道的唯一方法就是通过将SomeProperty声明为Object(Update1:现在我现在将此功能命名为泛型类)。 If I declare SomeProperty as ObjectBase, the compiler has no problem with SomeProperty=New DerivedClass, but it complains that Property1 is not a member of ObjectBase, which is true, but still, it works with SomeProperty as Object.
如果我将SomeProperty声明为ObjectBase,编译器对SomeProperty = New DerivedClass没有问题,但它抱怨Property1不是ObjectBase的成员,这是真的,但它仍然可以将SomeProperty用作Object。 This means the kind of behaviour I'm interested in already exists in .NET and it's implemented in Object class(Update1: Generic Classes).
这意味着我感兴趣的行为已经存在于.NET中,它在Object类(Update1:Generic Classes)中实现。
How to write a constraint to derived classes of ObjecBase? 如何将约束写入ObjecBase的派生类?
Public Class SomeOtherClass(Of T as {OnlyClassesWhichInherits(ObjectBase)})
Are you perhaps looking for… this? 你也许正在寻找......这个? :)
:)
Public Class SomeOtherClass(Of T As ObjectBase)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.