Using Settings with Complex Types

2019-04-22 04:37发布

问题:

I am using the Settings class in my .NET project. I notice in the editor that only certain types are available to be used as types for the individual properties in the Settings class. What if I wanted to have a property that was an enumeration from my code or a generic collection for instance? How would I implement that?

I'm guessing that I can do it in a separate file using the partial class mechanism (since Settings is already defined as a partial class) but I want to see if anyone agrees with that and if there may be a way to do it within the editor.

回答1:

Create a new "Settings" file to add a complex/user-defined type of choice. Here is a how-to for a Enum.

Step 1. Create a Settings file

Step 2. Browse for type

Step 3. Select type (Namespace.TypeName)

Step 4. Ta da - Done



回答2:

To get a custom class to show in that list, make sure it has a default constructor as one of it's constructing options. I learned this the hard way



回答3:

To answer Jeffrey's comment/question about whether Generic lists are possible in a settings file, the answer is yes. You just have to edit the Settings xml file manually. For example, if I have the following class:

public class UrlAlias
{
    public string Name { get; set; }
    public string BaseUrl { get; set; }
}

I can create a List of these by right clicking on my settings file and select Open With...

Then choose XML / Text Editor, and set the "Type" value to the fully qualified class name, i.e:

Type="System.Collections.Generic.List`1[MyProject.SomeNamespace.UrlAlias]"

The full settings xml would look like:

<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="MyProject.Properties" GeneratedClassName="Settings">
 <Profiles />
  <Settings>
    <Setting Name="UrlAliases" Type="System.Collections.Generic.List`1[CommonAddin.Data.DataSource.UrlAlias]" Scope="User">
      <Value Profile="(Default)"></Value>
    </Setting>
  </Settings>
</SettingsFile>

Once you do this, you should have a properly configured list of the custom settings object you created.



回答4:

Doing it in a separate file as a part of a partial class is totally acceptable.



回答5:

If you want to be able to populate complex objects through configuration files, I would suggest using some Dependency Injection Framework s.a. Spring.Net.