如何在 ConfigurationSection 中包含简单集合

发布于 2024-08-30 00:28:24 字数 537 浏览 6 评论 0原文

有没有办法让我包含一个简单的字符串数组,或 List在我的 ConfigurationSection 的自定义子类上? (或者简单数据对象的数组或通用列表?)

我正在熟悉新的(而且非常冗长的)ConfigurationSection、ConfigurationElement 和 ConfigurationElementCollection 类,但我还不是专家。

看起来 ConfigurationSection 应该自己处理简单的集合/列表,而不必为每个集合/列表创建一个自定义的 ConfigurationElementCollection 子类。但我在网上没有找到任何关于此能力的参考。

编辑:接受 Dan 的回复作为答案,因为这可能是我要得到的最接近“旧式”configSections 的东西。我总是发现任何 XmlSerialized 对象都可以轻松地成为 configSection,这很简单、灵活且优雅。我确信新框架更加强大;然而令人遗憾的是,对于简单的配置结构来说,它太麻烦了,我们不得不回到 String.Split()。

Is there a way for me to include a simple array of strings, or List<string> on my custom subclass of ConfigurationSection? (Or an array or generic list of simple data objects, for that matter?)

I'm becoming familiar with the new (and VERY verbose) ConfigurationSection, ConfigurationElement, and ConfigurationElementCollection classes, but I'm by no means an expert yet.

It seems like ConfigurationSection should handle simple collections/lists on its own, without me having to create a custom ConfigurationElementCollection subclass for each and every one. But I haven't found any reference to this ability online.

Edit: accepting Dan's response as the answer, since it's probably the closest thing I'm going to get to the "old style" configSections. I always found it easy, flexible, and elegant that any XmlSerializable object could easily become a configSection. I'm sure the new framework is more powerful; however it's sad that it is SO cumbersome for simple configuration contructs, that we're reduced to going back to String.Split().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

自在安然 2024-09-06 00:28:24

这是一个简单的例子。

//START CODE


//MyCompany.MyProject.csproj which results in MyCompany.MyProject.dll
//Add a Folder called "Configuration"

namespace MyCompany.MyProject.Configuration
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using System.Configuration;


    public class TransformationToDirectoryMapping : ConfigurationElement
    {

        private const string FRIENDLY_NAME = "FriendlyName";
        private const string PICKUP_FOLDER = "PickupFolder";

        [ConfigurationProperty(FRIENDLY_NAME, DefaultValue = "", IsKey = false, IsRequired = true)]
        public string FriendlyName
        {
            get
            {
                return ((string)(base[FRIENDLY_NAME]));
            }
            set
            {
                base[FRIENDLY_NAME] = value;
            }
        }

        [ConfigurationProperty(PICKUP_FOLDER, DefaultValue = "", IsKey = true, IsRequired = true)]
        public string PickupFolder
        {
            get
            {
                return ((string)(base[PICKUP_FOLDER]));
            }
            set
            {
                base[PICKUP_FOLDER] = value;
            }
        }



    }

    //-----------------------------------------------------------------------

    //-----------------------------------------------------------------------

    [ConfigurationCollection(typeof(TransformationToDirectoryMapping))]
    public class TransformationToDirectoryMappingCollection : ConfigurationElementCollection
    {

        protected override ConfigurationElement CreateNewElement()
        {
            return new TransformationToDirectoryMapping();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((TransformationToDirectoryMapping)(element)).PickupFolder;
        }


        public TransformationToDirectoryMapping this[int idx]
        {
            get
            {
                return (TransformationToDirectoryMapping)BaseGet(idx);
            }
        }

        new public TransformationToDirectoryMapping this[string key]
        {
            get
            {
                return (TransformationToDirectoryMapping)BaseGet(key);
            }
        }
    }

    //-----------------------------------------------------------------------

    //-----------------------------------------------------------------------

    public class TransformationToDirectoryMappingConfigSection : ConfigurationSection
    {
        private const string TRANSFORMATION_TO_DIRECTORY_MAPPINGS = "TransformationToDirectoryMappings";

        [ConfigurationProperty(TRANSFORMATION_TO_DIRECTORY_MAPPINGS)]
        public TransformationToDirectoryMappingCollection TransformationToDirectoryMappingItems
        {
            get { return ((TransformationToDirectoryMappingCollection)(base[TRANSFORMATION_TO_DIRECTORY_MAPPINGS])); }
        }
    }

    //-----------------------------------------------------------------------

    //-----------------------------------------------------------------------

    public static class MyRetriever
    {
        public const string MAPPINGS_CONFIGURATION_SECTION_NAME = "TransformationToDirectoryMappingsSection";

        public static TransformationToDirectoryMappingCollection GetTheCollection()
        {
            TransformationToDirectoryMappingConfigSection mappingsSection = (TransformationToDirectoryMappingConfigSection)ConfigurationManager.GetSection(MAPPINGS_CONFIGURATION_SECTION_NAME);
            if (mappingsSection != null)
            {
                return mappingsSection.TransformationToDirectoryMappingItems;
            }
            return null; // OOPS!

        }
    }

}

//配置文件的XML:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="TransformationToDirectoryMappingsSection" type="MyCompany.MyProject.Configuration.TransformationToDirectoryMappingConfigSection, MyCompany.MyProject"/>
  </configSections>

  <TransformationToDirectoryMappingsSection>
    <TransformationToDirectoryMappings>
      <add FriendlyName="Hello" PickupFolder="C:\WUWUTemp\pickups\pickup11\" />
      <add FriendlyName="GoodBye" PickupFolder="C:\WUWUTemp\pickups\pickup12\" />
    </TransformationToDirectoryMappings>
  </TransformationToDirectoryMappingsSection>
</configuration>

Here's a simple example.

//START CODE


//MyCompany.MyProject.csproj which results in MyCompany.MyProject.dll
//Add a Folder called "Configuration"

namespace MyCompany.MyProject.Configuration
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using System.Configuration;


    public class TransformationToDirectoryMapping : ConfigurationElement
    {

        private const string FRIENDLY_NAME = "FriendlyName";
        private const string PICKUP_FOLDER = "PickupFolder";

        [ConfigurationProperty(FRIENDLY_NAME, DefaultValue = "", IsKey = false, IsRequired = true)]
        public string FriendlyName
        {
            get
            {
                return ((string)(base[FRIENDLY_NAME]));
            }
            set
            {
                base[FRIENDLY_NAME] = value;
            }
        }

        [ConfigurationProperty(PICKUP_FOLDER, DefaultValue = "", IsKey = true, IsRequired = true)]
        public string PickupFolder
        {
            get
            {
                return ((string)(base[PICKUP_FOLDER]));
            }
            set
            {
                base[PICKUP_FOLDER] = value;
            }
        }



    }

    //-----------------------------------------------------------------------

    //-----------------------------------------------------------------------

    [ConfigurationCollection(typeof(TransformationToDirectoryMapping))]
    public class TransformationToDirectoryMappingCollection : ConfigurationElementCollection
    {

        protected override ConfigurationElement CreateNewElement()
        {
            return new TransformationToDirectoryMapping();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((TransformationToDirectoryMapping)(element)).PickupFolder;
        }


        public TransformationToDirectoryMapping this[int idx]
        {
            get
            {
                return (TransformationToDirectoryMapping)BaseGet(idx);
            }
        }

        new public TransformationToDirectoryMapping this[string key]
        {
            get
            {
                return (TransformationToDirectoryMapping)BaseGet(key);
            }
        }
    }

    //-----------------------------------------------------------------------

    //-----------------------------------------------------------------------

    public class TransformationToDirectoryMappingConfigSection : ConfigurationSection
    {
        private const string TRANSFORMATION_TO_DIRECTORY_MAPPINGS = "TransformationToDirectoryMappings";

        [ConfigurationProperty(TRANSFORMATION_TO_DIRECTORY_MAPPINGS)]
        public TransformationToDirectoryMappingCollection TransformationToDirectoryMappingItems
        {
            get { return ((TransformationToDirectoryMappingCollection)(base[TRANSFORMATION_TO_DIRECTORY_MAPPINGS])); }
        }
    }

    //-----------------------------------------------------------------------

    //-----------------------------------------------------------------------

    public static class MyRetriever
    {
        public const string MAPPINGS_CONFIGURATION_SECTION_NAME = "TransformationToDirectoryMappingsSection";

        public static TransformationToDirectoryMappingCollection GetTheCollection()
        {
            TransformationToDirectoryMappingConfigSection mappingsSection = (TransformationToDirectoryMappingConfigSection)ConfigurationManager.GetSection(MAPPINGS_CONFIGURATION_SECTION_NAME);
            if (mappingsSection != null)
            {
                return mappingsSection.TransformationToDirectoryMappingItems;
            }
            return null; // OOPS!

        }
    }

}

//XML for config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="TransformationToDirectoryMappingsSection" type="MyCompany.MyProject.Configuration.TransformationToDirectoryMappingConfigSection, MyCompany.MyProject"/>
  </configSections>

  <TransformationToDirectoryMappingsSection>
    <TransformationToDirectoryMappings>
      <add FriendlyName="Hello" PickupFolder="C:\WUWUTemp\pickups\pickup11\" />
      <add FriendlyName="GoodBye" PickupFolder="C:\WUWUTemp\pickups\pickup12\" />
    </TransformationToDirectoryMappings>
  </TransformationToDirectoryMappingsSection>
</configuration>
情绪失控 2024-09-06 00:28:24

应用程序设置体系结构

http://msdn.microsoft.com /en-us/library/8eyb2ct1.aspx

好吧,一个旧帖子,但当我遇到类似的情况时我想起了它:

...

如果你转到“项目/项目属性”(在 VS2008 或 VS2010 中)。
有一个“设置”选项卡。

如果添加新值....

其中一种类型称为:
System.Collections.Specialized.StringCollection

为其命名(我使用“FavoriteColors”)。

设置类型(按照上面的说明)。

设置值。

“字符串集合编辑器”显示“输入集合中的字符串(每行一个)”。

我输入:

红黄

黑白

将向您的 app.config 文件添加一些 xml

    <setting name="FavoriteColors" serializeAs="Xml">
        <value>
            <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                <string>red</string>
                <string>yellow</string>
                <string>black</string>
                <string>white</string>
            </ArrayOfString>
        </value>
    </setting>

(您最好完成这些步骤,而不是粘贴上面的 xml,因为(为了简洁起见)我没有将所有 xml 添加到生成的这篇文章中。

您应该能够通过代码“获取”这些值像这样:

private void ShowMyFavoriteColors()
{
            Properties.Settings.Default.FavoriteColors.Cast<string>().ToList().ForEach(myfavcolor =>
            {
                string temp = myfavcolor;
            });
}

注意,上述步骤将生成以下 C# 代码(为您创建的自动代码......它不是您创建的代码)
但代码如下所示:

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute(@"<?xml version=""1.0"" encoding=""utf-16""?>
<ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <string>red</string>
  <string>yellow</string>
  <string>black</string>
  <string>white</string>
</ArrayOfString>")]
        public global::System.Collections.Specialized.StringCollection FavoriteColors {
            get {
                return ((global::System.Collections.Specialized.StringCollection)(this["FavoriteColors"]));
            }
        }
    }
}

Application Settings Architecture

http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx

Ok, an old post, but I remembered it when I came across a similar situation:

...

If you go to Project / Project Properties (in VS2008 or VS2010).
There is a "Settings" tab.

If you add a new value....

One of the types is called:
System.Collections.Specialized.StringCollection

Give it a name (I used "FavoriteColors").

Set the type (as instructed above).

Set the value(s).

The "String Collection Editor" says "Enter the strings in the collection (one per line)".

I entered:

Red

Yellow

Black

White

This will add some xml to your app.config file.

    <setting name="FavoriteColors" serializeAs="Xml">
        <value>
            <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                <string>red</string>
                <string>yellow</string>
                <string>black</string>
                <string>white</string>
            </ArrayOfString>
        </value>
    </setting>

(You'll be better off going through the steps rather than pasting the xml above, because (for conciseness) I did not add all the xml to this post that is generated.

You should be able to "get at" the values via code like this:

private void ShowMyFavoriteColors()
{
            Properties.Settings.Default.FavoriteColors.Cast<string>().ToList().ForEach(myfavcolor =>
            {
                string temp = myfavcolor;
            });
}

Note, the steps above will produce the below C# code (auto code created for you.... it is not code you create)
but the code looks like this:

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute(@"<?xml version=""1.0"" encoding=""utf-16""?>
<ArrayOfString xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <string>red</string>
  <string>yellow</string>
  <string>black</string>
  <string>white</string>
</ArrayOfString>")]
        public global::System.Collections.Specialized.StringCollection FavoriteColors {
            get {
                return ((global::System.Collections.Specialized.StringCollection)(this["FavoriteColors"]));
            }
        }
    }
}
烦人精 2024-09-06 00:28:24

好吧,你要求简单。好吧,存储一系列字符串的最简单方法是使用分隔列表(例如,逗号分隔)。这样您就可以将其存储在一个元素中(例如在 appSettings 中)。

<add key="weekDays" value="Monday,Tuesday,Wednesday,Thursday,Friday"/>

当然,这有缺点,但在大多数情况下对于简单列表来说效果很好。然后,您可以使用 String.Split() 进行转换它返回到数组/列表。

否则,您将回到 ConfigurationSection 元素,我同意,这些元素非常冗长且难以使用。但恐怕我不知道任何其他方法(但很高兴被证明是错误的!)。

OK, you asked for simple. Well, the simplest way to store a series of strings would be to use a delimited list (say, comma separated). That way you can store it in just one element (say in appSettings).

<add key="weekDays" value="Monday,Tuesday,Wednesday,Thursday,Friday"/>

Of course, this has drawbacks but in most cases works well for a simple list. You can then use String.Split() to convert it back to an array/list.

Otherwise you are back to ConfigurationSection elements which, I agree, are very verbose and clumsy to work with. But I don't know of any other way, I'm afraid (but am happy to be proved wrong!).

一梦浮鱼 2024-09-06 00:28:24

我知道这个问题很久以前就已经得到了解答...但是在我的“ConfigurationElement”类中,对于字符串集合,我通常执行以下操作:

[ConfigurationProperty("myStringCollectionProperty", DefaultValue = "")]
[TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
public StringCollection MyStringCollectionProperty
{
    get { return (StringCollection)this["myStringCollectionProperty"]; }
    set { this["myStringCollectionProperty"] = value; }
 }

并且您可以从该属性中获取字符串列表

List<string> myStrings = config.MyStringCollectionProperty.Cast<string>.ToList()

I know that the question has been answered long time ago... but in my 'ConfigurationElement' classes, for string collection, I usually do the following:

[ConfigurationProperty("myStringCollectionProperty", DefaultValue = "")]
[TypeConverter(typeof(CommaDelimitedStringCollectionConverter))]
public StringCollection MyStringCollectionProperty
{
    get { return (StringCollection)this["myStringCollectionProperty"]; }
    set { this["myStringCollectionProperty"] = value; }
 }

And you can get a string list from this property with

List<string> myStrings = config.MyStringCollectionProperty.Cast<string>.ToList()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文