Using Settings with Complex Types

我是研究僧i 提交于 2019-12-10 02:24:44

问题


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.



来源:https://stackoverflow.com/questions/603501/using-settings-with-complex-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!