简体   繁体   English

从通用类型转换为其约束接口

[英]Converting from generic type to its constraint interface

I have created a generic class, with the constraint IComparable, as follows: 我创建了一个具有IComparable约束的通用类,如下所示:

Public Class Foo(Of T As IComparable)
    Private _f As T

    Public Sub New(ByVal f As T)
        _f = f
    End Sub

    Public Function GetBar() As Bar
        Return New Bar(Me) 'compiler error: Value of type Foo(of T) 
                           'cannot be converted to Foo(of IComparable)
    End Function

End Class

I have another class which takes as a constructor argument an object of the first class defined: 我有另一个类,它将定义的第一个类的对象作为构造函数参数:

Public Class Bar
    Private _foo As Foo(Of IComparable)

    Public Sub New(ByVal foo As Foo(Of IComparable))
        _foo = foo
    End Sub
End Class

However, I get the shown error when trying to create the Bar object. 但是,尝试创建Bar对象时出现显示的错误。

Can anybody explain why am I getting this error? 谁能解释为什么我会收到此错误? I would expect the compiler to know that type T is any IComparable type... 我希望编译器知道类型T是任何IComparable类型...

I have found a similar question here , but I don't know how to use it in my case. 我在这里找到了类似的问题,但我不知道该如何使用。

I would expect the compiler to know that type T is any IComparable type... 我希望编译器知道类型T是任何IComparable类型...

Yes, it knows that - but your Bar constructor is expecting a Foo(Of IComparable) not a Foo(Of T) where T implements IComparable . 是的,它知道这一点-但是您的Bar构造函数期望的是Foo(Of IComparable)而不是T实现IComparableFoo(Of T) You want generic covariance, but that can't be applied to classes in .NET (only interfaces and delegates). 您需要通用协方差,但不能将其应用于.NET中的类(仅适用于接口和委托)。

One option is to make Bar generic as well, with another type parameter T which is constrained to implement IComparable . 一种选择是使Bar通用,而另一种类型参数T受限于实现IComparable Then your Foo.GetBar() method could return a Bar(Of T) . 然后,您的Foo.GetBar()方法可以返回Bar(Of T)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM