微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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="[email protected]" 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐