How to include simple collections in ConfigurationSection

前端 未结 4 572
不思量自难忘°
不思量自难忘° 2020-12-20 11:49

Is there a way for me to include a simple array of strings, or List on my custom subclass of ConfigurationSection? (Or an array or generic list of simple data

4条回答
  •  时光说笑
    2020-12-20 12:14

    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.

        
            
                
                    red
                    yellow
                    black
                    white
                
            
        
    

    (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().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(@"
    
      red
      yellow
      black
      white
    ")]
            public global::System.Collections.Specialized.StringCollection FavoriteColors {
                get {
                    return ((global::System.Collections.Specialized.StringCollection)(this["FavoriteColors"]));
                }
            }
        }
    }
    

提交回复
热议问题