简体   繁体   English

何时在C#中使用Properties.Settings.Default

[英]When to use Properties.Settings.Default in C#

What are the best practices for using the Properties.Settings.Default config settings in C#? 在C#中使用Properties.Settings.Default配置设置的最佳实践是什么? I see it commonly, but I often don't know when to utilize it vs. when I should just hard code values. 我通常会看到它,但是我常常不知道何时使用它,何时应该使用硬代码值。 Thanks! 谢谢!

Basically, I try to avoid hardcoding values in code, mainly because if there's ever a need to change their value it requires a re-compile of the app. 基本上,我尝试避免对代码中的值进行硬编码,主要是因为如果需要更改其值,则需要重新编译应用程序。

It's usually beneficial to have some sort of common object that exposes all your settings via public properties so that you are referencing the settings the same way throughout the app. 拥有某种公共对象来公开所有设置,通常是有益的,这样您就可以在整个应用程序中以相同的方式引用这些设置。

Example: 例:

public static SomeReferenceClass
{
     public static string TimeOfDay { get{ return Properties.Settings.Default.TimeOfDay; }}
}

Then Later on to call it 然后稍后调用

SomeReferenceClass.TimeOfDay;

My rule of thumb has always been that if the values of the properties need to change without modifying the code then make them an external/configurable property. 我的经验法则一直是,如果需要在不修改代码的情况下更改属性的值,则将其设置为外部/可配置属性。 If you will never need to change their value, then they're a constant and can be hard-coded. 如果您永远不需要更改它们的值,那么它们就是一个常量,可以进行硬编码。

Basically, if these values need to be configured/changed put them in Properties.Settings.Default . 基本上,如果需要配置/更改这些值,则将它们放在Properties.Settings.Default You can hard code constants. 您可以对常数进行硬编码。

personally, I use the default setting when the user or application setting are not specified or persisted. 就个人而言,当未指定或保留用户或应用程序设置时,我使用默认设置。

I'd never hardcode a setting that might change based on any number of variables such as environment, user, application, or whatever. 我绝不会硬编码可能根据任何数量的变量(例如环境,用户,应用程序等)而改变的设置。

I generally create settings providers that implement an interface. 我通常会创建实现接口的设置提供程序。 That way, you can easily change out how to gather your configuration settings without changing the business logic. 这样,您可以轻松地更改如何收集配置设置,而无需更改业务逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM