.net中你喜欢哪种配置方法?为什么? [英] Which configuration method do you prefer in .net? Why?
本文介绍了.net中你喜欢哪种配置方法?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 您可以使用App.config;但它只支持键/值对。
- 您可以使用.Net配置,配置部分;但它可能真的很复杂。
- 您可以自己使用Xml序列化/反序列化;
- 您可以使用其他方法;他们可以是什么? ...
- You can use App.config; but it only supports key/value pairs.
- You can use .Net configuration, configuration sections; but it can be really complex.
- You can use Xml Serialization/Deserialization by yourself; your classes-your way.
- You can use some other method; what can they be? ...
您更喜欢这些方法或其他方法(如果有)为什么?
Which of these or other methods (if there are) do you prefer? Why?
推荐答案
当键值对不够时,我使用配置节,因为它们不复杂,复杂部分):
When key value pairs are not enough I use Configuration Sections as they are not complex to use (unless you need a complex section):
定义您的自定义部分:
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("LastName", IsRequired = true,
DefaultValue = "TEST")]
public String LastName
{
get { return (String)base["LastName"]; }
set { base["LastName"] = value; }
}
[ConfigurationProperty("FirstName", IsRequired = true, DefaultValue =
"TEST")]
public String FirstName
{
get { return (String)base["FirstName"]; }
set { base["FirstName"] = value; }
}
public CustomSection()
{
}
}
以编程方式创建您的版块(如果尚不存在):
Programmatically create your section (if it doesn't already exist):
// Create a custom section.
static void CreateSection()
{
try
{
CustomSection customSection;
// Get the current configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe");
// Create the section entry
// in the <configSections> and the
// related target section in <configuration>.
if (config.Sections["CustomSection"] == null)
{
customSection = new CustomSection();
config.Sections.Add("CustomSection", customSection);
customSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
}
catch (ConfigurationErrorsException err)
{
//manage exception - give feedback or whatever
}
}
以下CustomSection定义和实际CustomSection将为您创建:
Following CustomSection definition and actual CustomSection will be created for you:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" overrideModeDefault="Allow" restartOnExternalChanges="true" requirePermission="true" />
</configSections>
<CustomSection LastName="TEST" FirstName="TEST" />
</configuration>
现在检索您的版块属性:
Now Retrieve your section properties:
CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection");
string lastName = section.LastName;
string firstName = section.FirstName;
这篇关于.net中你喜欢哪种配置方法?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文