带点运算符的常数(VBA) [英] Constant With Dot Operator (VBA)

查看:75
本文介绍了带点运算符的常数(VBA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个恒定材料的目录,以便可以使用如下代码:

I want to have a catalog of constant materials so I can use code that looks like the following:

Dim MyDensity, MySymbol
MyDensity = ALUMINUM.Density
MySymbol = ALUMINUM.Symbol

显然铝的密度和符号不会发生变化,因此我希望它们是常数,但是为了简单起见,我喜欢点符号。

Obviously the density and symbol for aluminum are not expected to change so I want these to be constants but I like the dot notation for simplicity.

我看到了一些选择,但我没有

I see a few options but I don't like them.


  1. 为每种材料的每个特性制作常数。这似乎太多了,因为我可能拥有20种具有5个属性的材料。

  1. Make constants for every property of every material. That seems like too many constants since I might have 20 materials each with 5 properties.

Const ALUMINUM_DENSITY As Float = 169.34
Const ALUMINUM_SYMBOL As String = "AL"


  • 用所有材料定义一个枚举并进行返回属性的函数。密度不是常数,因为它的值是由函数返回的。

  • Define an enum with all the materials and make functions that return the properties. It's not as obvious that density is constant since its value is returned by a function.

    Public Enum Material
         MAT_ALUMINUM
         MAT_COPPER
    End Enum
    
    Public Function GetDensity(Mat As Material)
        Select Case Mat
            Case MAT_ALUMINUM
                GetDensity = 164.34
        End Select
    End Function
    


  • 它看起来好像不是Const Structs或Const Objects可以解决这个问题,但也许我错了(甚至可能不允许这样做)。有更好的方法吗?

    It doesn't seem like Const Structs or Const Objects going to solve this but maybe I'm wrong (they may not even be allowed). Is there a better way?

    推荐答案

    使VBA等效于静态类。常规模块可以具有属性,而没有任何内容表明它们不能为只读。我还将密度和符号包装为一种类型:

    Make VBA's equivalent to a "static class". Regular modules can have properties, and nothing says that they can't be read-only. I'd also wrap the density and symbol up in a type:

    'Materials.bas
    
    Public Type Material
        Density As Double
        Symbol As String
    End Type
    
    Public Property Get Aluminum() As Material
        Dim output As Material
        output.Density = 169.34
        output.Symbol = "AL"
        Aluminum = output
    End Property
    
    Public Property Get Iron() As Material
        '... etc
    End Property
    

    这非常接近您期望的用法语义:

    This gets pretty close to your desired usage semantics:

    Private Sub Example()
        Debug.Print Materials.Aluminum.Density
        Debug.Print Materials.Aluminum.Symbol
    End Sub
    

    如果您在同一个项目中,甚至可以删除显式的材料限定词(尽管我建议将其明确显示):

    If you're in the same project, you can even drop the explicit Materials qualifier (although I'd recommend making it explicit):

    Private Sub Example()
        Debug.Print Aluminum.Density
        Debug.Print Aluminum.Symbol
    End Sub
    

    这篇关于带点运算符的常数(VBA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆