如何在C#中为整个应用程序创建全局常量变量 [英] How to create global constant variables in C# for the entire application

查看:224
本文介绍了如何在C#中为整个应用程序创建全局常量变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含系统配置的表(即 system_name,system_time_zone .....

我试图找出最好的方法来自动读取配置,并准备好在我的应用程序中以任何形式读取值。

基本上,我想从表中读取配置,然后将它们设置为常量变量。当应用程序加载时,我可以以任何形式重新使用它们。



如何在C#中执行此操作?

可以创建一个 singleton class ,它会在启动时读取配置。



然而,我个人会研究依赖注入。在.NET中有很多的DI框架,这样你就可以获得更容易测试的代码,因为它是由配置而非获取的。 它来自某个可能难以伪造的地方。



您可能还想考虑将配置分成不同的相关部分,只注入与该类中的类相关的配置。例如,您可能希望一个类拥有所有与数据库相关的设置,另一个用于所有与电子邮件有关的设置(如果需要发送或检索电子邮件)等。这样可以明确哪些方面的配置的每个部分您的系统依赖于,这提高了可维护性。


I have a table that contains system configuration (ie. system_name, system_time_zone.....)

I am trying to identify the best approach to read the configuration automaticly and have the value ready to read in any form in my application.

Basically, I want to read the configuration from the table and then set them as a constant variables. When the application loads I can re-use them in any form.

How would I be able to do this in C#?

解决方案

Well, you could create a singleton class which would read the configuration on startup.

Personally, however, I would investigate dependency injection. There are lots of DI frameworks in .NET, and that way you'll have code which is easier to test, because it's given the configuration rather than it fetching it from somewhere which may be ugly to fake.

You may also want to consider separating the configuration out into different related parts, and only inject the parts of configuration that are relevant to a class into that class. For example, you might want one class holding all of the database-related settings, another for all the email-related settings (if it needs to send or retrieve emails) etc. That way it makes it obvious which aspects of configuration each part of your system depends on, which improves maintainability.

这篇关于如何在C#中为整个应用程序创建全局常量变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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