您可以在设置文件中使用通用列表(T)吗?

时间:2009-06-04 17:09:52

标签: .net generics app-config

在我的设置文件中,我希望有一个类型为List(Myclass)的设置....我在网上找不到任何可以做到这一点的内容。有可能吗?

5 个答案:

答案 0 :(得分:12)

我同意Meta-Knight的继承解决方案是最好的,但是可以通过手动编辑设置XML文件来实现。在Solution Explorer中,转到:解决方案&gt;项目&gt;属性&gt; Settings.settings。右键单击Settings.settings并选择“打开方式”。选择“XML(文本)编辑器”。然后在<Settings>

中插入以下内容
<Setting Name="TestGenericList" Type="System.Collections.Generic.List&lt;int&gt;" Scope="User">
  <Value Profile="(Default)" />
</Setting>

保存,并且有效。

不幸的是,它似乎不适用于需要两种或更多类型的泛型类型,因为该属性中不允许使用逗号。甚至对它进行实体编码(&#x002C;)也无济于事。

当您在设置设计器中编辑设置文件时,以下内容会导致错误“路径中的字符非法”:

<Setting Name="TestGenericDictionary" Type="System.Collections.Generic.Dictionary&lt;string&#x002C;string&gt;" Scope="User">
  <Value Profile="(Default)" />
</Setting>

答案 1 :(得分:8)

我假设你在谈论用户设置......

我不知道您是否可以指定泛型类型,但是如果您创建自己的非泛型类型(继承自List(MyClass)),那么您可以将此类型指定为您的用户设置而没有任何问题。 / p>

类似的东西:

Public Class MyClassList 
    Inherits List(Of MyClass)

End Class

然后你应该能够浏览MyClassList。

答案 2 :(得分:3)

在提供此答案的解决方案时,我可能会稍晚一些,但您可以将通用设置属性包含在项目中不同文件的分部类中,因此“设置设计器”不会覆盖任何自定义您添加的代码。

在我的情况下(使用VB.NET),我想在My.Settings中存储Dictionary(Of String, String),除了字典必须序列化为Binary,因为它不容易序列化为XML。我从设计器中删除了设置属性,然后将文件Settings.Extended.vb添加到我的项目中,其中包含以下代码:

'** Keeping My.Settings.FormLayouts out of Settings.Designer.vb so that this custom code is not overwritten by Visual Studio.'

Namespace My
   Partial Friend NotInheritable Class MySettings
      <Configuration.UserScopedSettingAttribute(), _
       DebuggerNonUserCodeAttribute(), _
       Configuration.SettingsSerializeAs(Configuration.SettingsSerializeAs.Binary)> _
      Public Property FormLayouts() As Dictionary(Of String, String)
         Get
            Return CType(Me("FormLayouts"), Dictionary(Of String, String))
         End Get
         Set(ByVal value As Dictionary(Of String, String))
            Me("FormLayouts") = value
         End Set
      End Property
   End Class
End Namespace

FormLayouts属性仍然是My.Settings的一部分,将像往常一样加载和保存,但在应用程序的设置设计器中添加更多设置不会覆盖上面的代码。

答案 3 :(得分:0)

您可以将List<T>序列化为字符串,然后将其放入设置文件中。

那会有用吗?

答案 4 :(得分:-1)

是的,只需输入List&lt; SomeType&gt;  手动进入类型字段,它应该可以工作。