Custom app.config Config Section Handler

前端 未结 1 1617
Happy的楠姐
Happy的楠姐 2020-11-28 23:54

What is the correct way to pick up the list of \"pages\" via a class that inherits from System.Configuration.Section if I used a app.config like this?



        
相关标签:
1条回答
  • 2020-11-29 00:43

    First you add a property in the class that extends Section:

    [ConfigurationProperty("pages", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(PageCollection), AddItemName = "add")]
    public PageCollection Pages {
        get {
            return (PageCollection) this["pages"];
        }
    }
    

    Then you need to make a PageCollection class. All the examples I've seen are pretty much identical so just copy this one and rename "NamedService" to "Page".

    Finally add a class that extends ObjectConfigurationElement:

    public class PageElement : ObjectConfigurationElement {
        [ConfigurationProperty("title", IsRequired = true)]
        public string Title {
            get {
                return (string) this["title"];
            }
            set {
                this["title"] = value;
            }
        }
    
        [ConfigurationProperty("url", IsRequired = true)]
        public string Url {
            get {
                return (string) this["url"];
            }
            set {
                this["url"] = value;
            }
        }
    }
    

    Here are some files from a sample implementation:

    • Sample config
    • Collection and element classes
    • Config section class
    0 讨论(0)
提交回复
热议问题