AppSettings 与 applicationSettings (.NET app.config/Web.config) 的优缺点 [英] Pros and cons of AppSettings vs applicationSettings (.NET app.config / Web.config)
问题描述
在开发 .NET Windows 窗体应用程序时,我们可以选择那些 App.config
标记来存储我们的配置值.哪个更好?
基本的
更容易处理 - 只需添加一个
缺点是:没有类型检查,例如您无法安全地假设您想要配置的号码确实是一个数字 - 有人可以将字符串放入该设置中.....您只需以 ConfigurationManager["(key)"]
访问它然后由你来决定你在处理什么.
此外,随着时间的推移,<appSettings>
可能会变得相当复杂和凌乱,如果您的应用程序的很多部分开始将内容放入其中(还记得旧的 windows.ini 文件吗?:-)).
如果可以,我更愿意并推荐使用您自己的配置部分 - 使用 .NET 2.0,这真的变得非常简单,这样,您可以:
- a) 在代码中定义您的配置设置并使其类型安全并检查
- b) 您可以将您的设置与所有人完全分开别人的.您也可以重复使用您的配置代码!
在 CodeProject 上有一系列关于您揭开 .NET 2.0 配置系统神秘面纱的非常好的文章:
强烈推荐!Jon Rista 出色地解释了 .NET 2.0 中的配置系统.
When developing a .NET Windows Forms Application we have the choice between those App.config
tags to store our configuration values. Which one is better?
<configuration>
<!-- Choice 1 -->
<appSettings>
<add key="RequestTimeoutInMilliseconds" value="10000"/>
</appSettings>
<!-- Choice 2 -->
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" >
<section name="Project1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5612342342" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<Project1.Properties.Settings>
<setting name="TABLEA" serializeAs="String">
<value>TABLEA</value>
</setting>
</Project1.Properties.Settings>
</applicationSettings>
</configuration>
The basic <appSettings>
is easier to deal with - just slap in a <add key="...." value="..." />
entry and you're done.
The downside is: there's no type-checking, e.g. you cannot safely assume your number that you wanted to configure there really is a number - someone could put a string into that setting..... you just access it as ConfigurationManager["(key)"]
and then it's up to you to know what you're dealing with.
Also, over time, the <appSettings>
can get rather convoluted and messy, if lots of parts of your app start putting stuff in there (remember the old windows.ini file? :-)).
If you can, I would prefer and recommend using your own configuration sections - with .NET 2.0, it's really become quite easy, That way, you can:
- a) Define your configuration settings in code and have them type-safe and checked
- b) You can cleanly separate YOUR settings from everyone else's. And you can reuse your config code, too!
There's a series of really good articles on you to demystify the .NET 2.0 configuration system on CodeProject:
Highly recommended! Jon Rista did a great job explaining the configuration system in .NET 2.0.
这篇关于AppSettings 与 applicationSettings (.NET app.config/Web.config) 的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!