c# - 如何在 ConfigurationElementCollection 中拥有自定义属性?

标签 c# .net-4.0 configuration-files

配置如下

<MyCollection default="one">
  <entry name="one" ... other attrubutes />
  ... other entries
</MyCollection>

当实现一个 MyCollection 时,我应该如何处理“默认”属性?

最佳答案

假设您有这个 .config 文件:

<configuration>
    <configSections>
        <section name="mySection" type="ConsoleApplication1.MySection, ConsoleApplication1" /> // update type  & assembly names accordingly
    </configSections>

    <mySection>
        <MyCollection default="one">
            <entry name="one" />
            <entry name="two" />
        </MyCollection>
    </mySection>
</configuration>

然后,使用这段代码:

public class MySection : ConfigurationSection
{
    [ConfigurationProperty("MyCollection", Options = ConfigurationPropertyOptions.IsRequired)]
    public MyCollection MyCollection
    {
        get
        {
            return (MyCollection)this["MyCollection"];
        }
    }
}

[ConfigurationCollection(typeof(EntryElement), AddItemName = "entry", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class MyCollection : ConfigurationElementCollection
{
    protected override ConfigurationElement CreateNewElement()
    {
        return new EntryElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        if (element == null)
            throw new ArgumentNullException("element");

        return ((EntryElement)element).Name;
    }

    [ConfigurationProperty("default", IsRequired = false)]
    public string Default
    {
        get
        {
            return (string)base["default"];
        }
    }
}

public class EntryElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
    public string Name
    {
        get
        {
            return (string)base["name"];
        }
    }
}

您可以使用“默认”属性读取配置,如下所示:

    MySection section = (MySection)ConfigurationManager.GetSection("mySection");
    Console.WriteLine(section.MyCollection.Default);

这将输出“一”

关于c# - 如何在 ConfigurationElementCollection 中拥有自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8829414/

相关文章:

.net - Entity Framework 和 .NET 4.0 的 LINQ to SQL 之间有什么区别?

c# - 如何判断是鼠标选中还是按键选中?

java - 不明确的 setter 方法导致分配属性值出现问题

c# - 面向对象设计与数据库设计

c# - 为什么 task.Wait 不会在非 ui 线程上死锁?还是我只是幸运?

entity-framework - EF 4.1 在多对多关系上映射继承

intellij-idea - 是否有引用网站/手册记录了intellij的.iml,.iws和.ipr文件的结构?

visual-studio-2010 - 配置部分设计器替代方案

c# - 如何从 C# 中的 ArrayList 中删除 TopMost 元素

c# - 连接池工作正常吗?