加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#的自定义配置

发布时间:2020-12-15 22:14:34 所属栏目:百科 来源:网络整理
导读:我有一个自定义配置的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"
我有一个自定义配置的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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读