我可以为ConfigurationManager类创建自定义方法吗

本文关键字:自定义方法 创建 ConfigurationManager 我可以 | 更新日期: 2023-09-27 18:22:10

我的web配置如下:

  <appSettings>
    <add key="One" value="1" xdt:Transform="Insert"/>
  </appSettings>

如果我需要访问值1,我可以写下面的代码:

ConfigurationManager.AppSettings("One");

但是如果网络配置像

  <countryAppSettings>
    <add key="Two" value="2" xdt:Transform="Insert"/>
  </countryAppSettings>

我可以使用ConfigurationManager类的助手类访问以下形式的值吗

ConfigurationManager.CountryAppSettings("Two");

这在c#中可能吗?

我可以为ConfigurationManager类创建自定义方法吗

是的,您可以这样做,尽管您也需要在配置文件中包含一个自定义配置部分。这里有一篇MSDN文章描述了如何做到这一点

因此,您需要首先添加自定义配置部分:

<configuration>
  <configSections>
    <sectionGroup name="countrySettings">
      <section name="countrySetting" type="Custom.CountrySettingSection" allowLocation="true" allowDefinition="Everywhere" />
    </sectionGroup>
  </configSections>
</configuration>

然后,你通常会像这样定义你的设置,如果你有一个非常丰富的对象,这很好:

<countrySetting customKey="2">
   <richerObject>2</richerObject>
</countrySetting>

然后你需要一个像这样构建的支持对象:

namespace Custom
{
 public class CountrySettingSection : ConfigurationSection
    {
        // Create a "customKey" attribute.
        [ConfigurationProperty("customKey", DefaultValue = "0", IsRequired = false)]
        public int CustomKey
        {
            get
            { 
                return (int)this["customKey"]; 
            }
            set
            { 
                this["customKey"] = value; 
            }
        }
}
  1. 你不能那样创造。也许应该访问这个链接https://msdn.microsoft.com/en-us/library/bb383977.aspx
  2. ConfigurationManager.AppSetting是属性,没有方法。这属性类型是NameValueCollection,你可以像这个一样使用

    ConfigurationManager.AppSettings["One"]ConfigurationManager.AppSettings.GetValues("One")

  3. 您可以自定义web.confighttps://msdn.microsoft.com/en-us/library/2tw134k3.aspx