在程序中存储常量或常用值的最佳方法是什么? [英] What is the best way to store constants or often used values in your program ?

查看:92
本文介绍了在程序中存储常量或常用值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello all



如果你有常量,经常使用变量(无论名称是什么),存储它们的最佳方法是什么?它会有所作为吗?



代码(静态类,常量变量,枚举,等等)

配置文件(appsettings例如)

数据库

Hello all

If you have constants, very often used variables (whatever the name is), what is the best way to store them ? does it make a difference ?

Code (static class, const variables, enum, ... etc.)
config file ( appsettings for example )
Database

推荐答案

如果它们确实是常数,那么你可以使用...常量。以下是一个示例,可以很好地解释何时/为何使用它们 http://www.dotnetperls.com/const [ ^ ]



如果您有一组相关数据,请点击 http://www.dotnetperls.com/enum [ ^ ]非常实用且类型安全。



例如
If they are indeed constant then you can use ... constants. Here is an example with a reasonably good explanation of when/why to use them http://www.dotnetperls.com/const[^]

If you have a set of related data then enums http://www.dotnetperls.com/enum[^] are useful and type-safe.

E.g.
enum WorkingDays
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday
}

清楚地表明我星期五没有工作(一厢情愿),我的工作周从星期一开始。这也意味着编译器会告诉我,我是否做了一些愚蠢的事情,比如

clearly shows that I don't work on Fridays (wishful thinking) and my working week starts on a Monday. It also means that the compiler will tell me if I do something silly like

WorkingDays wd = 6;

- 这比找出我的程序更好实际上正在运行。



如果你的东西相对不变但将来可能会改变,那么AppSettings可能是合适的http://www.dotnetperls.com/settings [ ^ ]。这将是连接字符串,文件位置等等。



我还使用数据库存储常备数据,其中存在大量常量值或半他们定期更改的常数(例如ISA限制,税收门槛等)。



所以你看到没有真正的最佳概念 - 它取决于你所编写的程序的性质,你必须对每个案例使用你的判断。

- which is better than finding out when my program is actually running.

If you have things that are relatively constant but may change in the future then AppSettings may be appropriate http://www.dotnetperls.com/settings[^]. This would be things like connection strings, file locations etc.

I have also used a Database to store "standing data" where there are lots of constant values or semi-constant where they change on a regular basis (e.g. ISA Limits, tax thresholds etc).

So you see there is not really an overall concept of "best" - it depends on the nature of the program you are writing, and you will have to use your judgement on each individual case.


这篇关于在程序中存储常量或常用值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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