【问题标题】:Converting from generic type to its constraint interface从泛型类型转换为其约束接口
【发布时间】:2014-11-11 18:13:15
【问题描述】:

我创建了一个泛型类,约束为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

我有另一个类,它以定义的第一个类的对象作为构造函数参数:

Public Class Bar
    Private _foo As Foo(Of IComparable)

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

但是,我在尝试创建 Bar 对象时收到所示错误。

谁能解释我为什么会收到这个错误?我希望编译器知道类型 T 是任何 IComparable 类型...

我发现了一个类似的问题here,但我不知道如何在我的情况下使用它。

【问题讨论】:

    标签: vb.net generics type-conversion


    【解决方案1】:

    我希望编译器知道类型 T 是任何 IComparable 类型...

    是的,它知道 - 但是您的 Bar 构造函数期望 Foo(Of IComparable) 而不是 Foo(Of T) 其中 T 实现 IComparable。您需要泛型协方差,但这不能应用于 .NET 中的类(仅限接口和委托)。

    一个选项是使Bar 也通用,另一个类型参数T 被限制为实现IComparable。然后你的Foo.GetBar() 方法可以返回一个Bar(Of T)

    【讨论】:

      猜你喜欢
      • 2020-09-16
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多