spi*_*dal 18 .net configuration
您更喜欢这些或其他方法中的哪一种(如果有的话)?为什么?
Joh*_*dol 21
当键值对不够时,我使用配置节,因为它们使用起来并不复杂(除非您需要复杂的部分):
定义自定义部分:
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()
{
}
}
Run Code Online (Sandbox Code Playgroud)
以编程方式创建您的部分(如果它尚不存在):
// 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
}
}
Run Code Online (Sandbox Code Playgroud)
在CustomSection定义之后,将为您创建实际的CustomSection:
<?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>
Run Code Online (Sandbox Code Playgroud)
现在检索您的部分属性:
CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection");
string lastName = section.LastName;
string firstName = section.FirstName;
Run Code Online (Sandbox Code Playgroud)
Mit*_*ers 12
如果我可以使用它,我将使用App.Config,但是,如果我需要更复杂的东西,我将使用自定义配置部分.是的,在开始时理解它是一件痛苦的事情,但是对于所有设置而言,统一的配置源和熟悉的配置值得花时间投资.
归档时间: |
|
查看次数: |
3515 次 |
最近记录: |