C#的自定义配置
作者:互联网
我有一个自定义配置的App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="wsa" type="WSASRT.SRT.WSA.WsaConfig" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<wsa>
<src E="Foo@bar.com" CN="AnotherFoo" OU="AnotherBar" />
<!-- More elements -->
</wsa>
</configuration>
以及映射类
namespace WSASRT.SRT.WSA
{
class WsaConfig : ConfigurationSection
{
[ConfigurationProperty("src")]
public SrcElement Src { get { return (SrcElement)this["src"]; } }
}
public class SrcElement : ConfigurationElement
{
[ConfigurationProperty("E")]
public string E { get { return (String)this["E"]; } }
[ConfigurationProperty("CN")]
public string CN { get { return (String)this["CN"]; } }
}
}
我的Program.cs看起来像:
class Program
{
static void Main(string[] args)
{
WsaConfig config = new WsaConfig();
Console.WriteLine(config.Src.CN);
Console.ReadLine();
}
}
当我运行它时,我得到一个空字符串,但我应该得到“AnotherFoo”.我究竟做错了什么?
解决方法:
替换下面的第一行,以便从配置文件&中读取它.没有实例化新的..
WsaConfig config = ConfigurationManager.GetSection("wsa") as WsaConfig;
标签:c,c-4-0,app-config,custom-configuration 来源: https://codeday.me/bug/20190708/1400623.html