gpt4 book ai didi

.net - VB.NET 中常量的容器

转载 作者:行者123 更新时间:2023-12-02 05:39:15 25 4
gpt4 key购买 nike

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

我想为该范围使用 Structure,但编译器强制我为该结构声明一个私有(private)成员。

  ' 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)

最佳答案

在我看来,为此目的的最佳选择是创建一个仅包含共享的静态成员和常量的(私有(private))类。您无需创建对象,您可以根据需要控制辅助功能。

   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当你使用模块时。我更喜欢“标准-.NET”方式,而不是仅使用 Visual Basic 的方式。此外,您可以更好地控制它的可访问性,并且可以将其作为内部类。这实际上是 VB.NET对应于 C# static class .

关于.net - VB.NET 中常量的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3139787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com