.net - 通用类 (T) - 从一系列类型 VB.Net 中指定

标签 .net vb.net generics

这是我要开发的代码:

  Public Structure Statistic(Of t)
        Dim maxStat As t
        Dim curStat As t

        Public Sub New(ByVal pValue As t)
            maxStat = pValue
            curStat = pValue
        End Sub

        Public Property Level() As t
            Get
                Return curStat
            End Get
            Set(ByVal value As t)
                curStat = value
                If curStat > maxStat Then curStat = maxStat
            End Set
        End Property
    End Structure

它不会编译,因为我得到一个错误,'>' is not defined for types of T and T。无论如何我可以指定约束来保证 T 是数字类型吗?

这是经过用户的修改和建议后我目前得到的。它仍然无法正常工作。我是否必须将 T 的值更改为 IComparable?一定有一些非常简单的事情我搞砸了。

   Public Structure Statistic(Of T As IComparable(Of T))
        Dim maxStat As T
        Dim curStat As T

        Public Sub New(ByVal pValue As T)
            maxStat = pValue
            curStat = pValue
        End Sub

        Public Property Statistic() As T
            Get
                Return curStat
            End Get
            Set(ByVal value As T)
                If value > maxStat Then

                End If
            End Set
        End Property
    End Structure

最佳答案

您可以将 T 限制为 IComparable .这样你就知道 curStat 和 maxStat 都有一个 CompareTo 方法,你可以用它来确定一个是否大于另一个。

关于.net - 通用类 (T) - 从一系列类型 VB.Net 中指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3358416/

相关文章:

.net - 为每个 TabItem 重用网格行定义

除非指定参数类型,否则 Java 无法编译通用 lambda 参数

swift - 返回通用协议(protocol) swift 的特殊类型的方法

java - 类抽象和泛型

.net - 托管 C++ 中的数组初始化

C#反序列化xml文件形成List<T>

c# - LibGit2Sharp 如何解决冲突?

vb.net - 仅编译 ffmpeg 解码而不使用音频编解码器

vb.net - 在 Visual Basic 中使用语句

c# - Android转WP7绝对新手问题: C# or VB?