简体   繁体   English

在vb.net中转换自定义类以接受变量类型

[英]Converting a custom class to accept a variable type in vb.net

I am fairly new to custom classes in VB.Net and am having a bit of an issue with assigning a value from my class to the class object. 我对VB.Net中的自定义类是相当陌生的,并且在将类中的值分配给类对象时遇到一些问题。 See code below: 参见下面的代码:

Public Class NType
    Public Const Small As Double = 1
    Public Const Medium As Double = 2
    Public Const Large As Double = 3

'Another thing I tried...
    Public Shared ReadOnly Property _Small As Double
        Get
            Return Small
        End Get
    End Property
End Class

However as soon as I do: 但是,只要我这样做:

Dim NType1 as NType = NType.Small

I get an error to say Value of type 'Double' cannot be converted to 'Harris.NType' 我收到一个错误消息, Value of type 'Double' cannot be converted to 'Harris.NType'

I assume there will be some sort of way to allow this (in a similar vein to how, say Color works) 我认为将有某种方式允许这样做(与Color工作原理类似)

I think that, from the looks of it, what you actually want is an enumeration rather than a class. 从外观上看,我认为您真正想要的是枚举而不是类。

Public Enum NType

    Small
    Medium
    Large

End Enum

Dim nType1 As NType = NType.Small

You can specify the actual values but, generally, those values should be irrelevant and all that matters is that they're unique and don't change. 您可以指定实际值,但是通常,这些值应该无关紧要,重要的是它们是唯一的并且不会更改。 By default, an enumeration is stored as an Integer but you can specify any integral type. 默认情况下,枚举存储为Integer但您可以指定任何整数类型。 By default, the first value is equal to zero and each subsequent value is equal to 1 more than the previous one. 默认情况下,第一个值等于零,并且每个后续值都比前一个值大1。 You can specify one or more values if you need to though. 如果需要,您可以指定一个或多个值。

Public Enum NType As Short

    Small = 1
    Medium
    Large

End Enum

The values still increment by 1 but will now start at 1 instead of zero. 值仍然增加1,但现在将从1开始而不是零。 You should only do that if you will be using the same numeric values to represent the same data elsewhere and the two must match. 仅当您将使用相同的数值来表示其他位置的相同数据且两者必须匹配时,才应这样做。 Don't do it just because you can. 不要仅仅因为可以就这样做。

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

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