可覆盖的常数? [英] Overridable Constant?

查看:118
本文介绍了可覆盖的常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我应该将其设为公共成员,但我一直认为它应该是一个常数。

Maybe I should just make this a public member, but I keep thinking it should be a constant.

场景

我有一些要渲染为PDF的表单(使用 iTextSharp )。在代码中,表单本身都继承了基类( OrderForm )。在 OrderForm 中,有一列用于对齐PDF渲染内容时用于测量的常量列表,例如 LEFT_MARGIN 等。这些常量用于几个函数中确定要去的地方。

I have forms I'm rendering into PDFs (using iTextSharp). In code, the forms themselves all inherit a base class (OrderForm). Within OrderForm, there are a list of constants that I use for measurements when aligning things for the PDF rendering, such as LEFT_MARGIN, etc. These constants are used in several functions to determine where things go.

所有形式实际上都是相同的,因为它们由相同的组件(标题,地址)组成盒子,物品等)。但是,表格的布局略有不同...在一种表格上,地址框距离右边一英寸(以适合雇主使用的信封窗口)。

All the forms are virtually identical as they are comprised of the same components (header, address boxes, items, etc). However, the layout of the forms differ slightly... on one form, the address box is an inch further to the right (to fit in the envelope window my employer uses).

问题

不是为每个边距创建大量常量,而是填充,等等对于基类中的每种形式,例如: PURCHASE_ORDER_LEFT_MARGIN INVOICE_LEFT_MARGIN ,等等,不是吗更好地创建可以在 inheritee [sic]对象中设置的可覆盖的 LEFT_MARGIN ?我的理由是,它是一个 常量,在该对象内不会更改,只会形成形式,而基类中的呈现将相对于该常量保持不变。

Rather than create a slew of constants for each margin, padding, blah blah for each form in the base class, eg: PURCHASE_ORDER_LEFT_MARGIN, INVOICE_LEFT_MARGIN, etc, wouldn't it be better to create an overridable LEFT_MARGIN that can be set in the "inheritee" [sic] object? My reasoning is that it is a constant that will not change within that object, only form to form, yet the renderings in the base class will remain relative to whatever that constant is.

我知道我可以简单地创建一个公共成员并设置其值,但是我想知道正确的方法。

I know I could simply create a public member and set its value, but I'd like to know the right way to go about this.

谢谢。

推荐答案

常量是隐式静态的(共享的)

使用只读属性,然后您可以选择在任何时候覆盖它或任何需要的地方。

Use a Readonly Property instead, and then you can choose to override it whenever or wherever need be.

一个简单的例子....

A quick example ....

Class BaseClass

    ' Assume this field is set with a value from somewhere else'
    Private _leftmargin As Integer

    Overridable Readonly Property LEFT_MARGIN  As Integer
        Get
            Return _leftmargin
        End Get
    End Property
End Class

Class DerivedClass1
    Inherits BaseClass

    Overrides Readonly Property LEFT_MARGIN  As Integer
        Get
            Return 5 'specialized case for this class'
        End Get
    End Property
End Class

Class DerivedClass2
    Inherits BaseClass

    'uses base class LEFT_MARGIN'

End Class

这篇关于可覆盖的常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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