代码之家  ›  专栏  ›  技术社区  ›  serhio

VB.NET中常量的容器

  •  2
  • serhio  · 技术社区  · 15 年前

    假设我有一些相互依赖的常量,我决定把它们放在一个容器中,而不是把它们作为单独的常量放在一个类中。

    我想用一个 Structure

      ' Compile error: at least one private member is needed.
      Private Structure BandSizes 
        Const BandHeight As Short = HourHeight + 20
        Const HourHeight As Short = HalfHourHeight + 20
        Const HalfHourHeight As Short = LineHeight + PictureHeight + 20
        Const PictureHeight As Short = 20
        Const LineHeight As Short = StopHeight + 10
        Const LineWidth As Short = 50
        Const StopHeight As Short = 30
      End Structure
    

    由于我只有几个整数常量,我应该创建一个共享(静态)类吗?

    平台:VB.NET(.NET 2)

    4 回复  |  直到 12 年前
        1
  •  9
  •   Peter Mortensen Pieter Jan Bonestroo    12 年前

    在我看来,实现这个目的的最佳选择是创建一个(私有)类,该类只包含共享的、静态的成员和常量。您不需要创建对象,并且可以根据需要控制可访问性。

       Private NotInheritable Class BandSizes
            Public Const BandHeight As Short = HourHeight + 20
            Public Const HourHeight As Short = HalfHourHeight + 20
            Public Const HalfHourHeight As Short = LineHeight + PictureHeight + 20
            Public Const PictureHeight As Short = 20
            Public Const LineHeight As Short = StopHeight + 10
            Public Const LineWidth As Short = 50
            Public Const StopHeight As Short = 30
    
            Private Sub New()
            End Sub
        End Class
    

    注: NotInheritable 类的声明中需要,因为它是编译器将生成的 CIL 使用模块时。我更喜欢“standard-.NET”,而不是只使用VisualBasic的东西。此外,您对它的可访问性有更多的控制,并且可以将它作为内部类。这实际上是 VB.NET 对应于 C# static class .

        2
  •  6
  •   Peter Mortensen Pieter Jan Bonestroo    12 年前

    因为它是 VB.NET ,如果它们是真正的全局常量,并且它们本身的名称就足够了,您还可以创建一个模块来保存它们。

    另外,请注意,如果这些常量是从外部程序集访问的,那么如果这些常量的值可以更改,则可能会出现问题。因此,如果这些是公共的,并且放在类库中,例如,最好将它们设置为只读,而不是常量。

        3
  •  2
  •   Peter Mortensen Pieter Jan Bonestroo    12 年前

    Constants in .NET 然后决定使用“const”还是“readonly”。

        4
  •  -2
  •   Richard    15 年前

    enum 可能是更好的选择。不确定VB语法,但C#会是:

    internal enum BandSizes {
      BandHeight = HourHeight + 20,
      HourHeight = HalfHourHeight + 20,
      HalfHourHeight = LineHeight + PictureHeight + 20,
      PictureHeight = 20,
      LineHeight = StopHeight + 10,
      LineWidth = 50,
      StopHeight = 30,
    }
    

    (注。如果这是命名空间范围, internal 是最严格的访问,但是 private

    编辑:以下是VB版本:

    Friend Enum BandSizes
        BandHeight = HourHeight + 20
        HourHeight = HalfHourHeight + 20
        HalfHourHeight = LineHeight + PictureHeight + 20
        PictureHeight = 20
        LineHeight = StopHeight + 10
        LineWidth = 50
        StopHeight = 30
    End Enum
    

    在哪里? Friend Private

    推荐文章