【问题标题】:How do I store and retrieve an Enum in My.Settings如何在 My.Settings 中存储和检索枚举
【发布时间】:2021-12-27 16:51:17
【问题描述】:

我正在尝试通过组合框在 My.Settings 中存储和检索 ContentAlignment 枚举。我已经在项目设置中设置了这个类型。我正在使用相关 Enum 值填充设置表单上的组合框:

With ControlAnchorCB
        .Items.AddRange([Enum].GetNames(GetType(ContentAlignment)))
End With

然后我尝试将组合框设置为 My.Settings 中的组合框:

ControlAnchorCB.SelectedItem = My.Settings.ConnectorControlAnchor

但没有显示值。我还尝试将选定的组合框值保存回 My.Settings :

My.Settings.ConnectorControlAnchor = ControlAnchorCB.SelectedItem

但是,这会导致异常:“System.InvalidCastException: '从字符串“MiddleCenter”到类型“Integer”的转换无效。'”

更新:另一个限制是我在 Framework 3.5(必须是这个版本)和 vb.net 中编码。因此,Enum.TryParse 不可用。

我怎样才能做到这一点?

【问题讨论】:

  • 查看 Enum.TryParse
  • 保存枚举时,将其转换为 int 或在枚举上调用 .ToString()。当您从设置中恢复它时,获取字符串或 int 值,并使用 Enum.TryParse 或将 int 转换回枚举。设置一个断点,看看它是否有效...
  • 谢谢两位。我忘了提到我必须在 Framework 3.5 和 vb.net 中执行此操作。因此, Enum.TryParse 不可用。 :(

标签: .net enums my.settings


【解决方案1】:

费了好大劲才解决:

    ' My.Settings.ConnectorControlAnchor Type is set to ContentAlignment in Project Settings.   
    
    Public Function TryParse(Of TEnum As {Structure, IConvertible})(ByVal value As String, <Out> ByRef result As TEnum) As Boolean
        Dim retValue = If(value Is Nothing, False, [Enum].IsDefined(GetType(TEnum), value))
        result = If(retValue, CType([Enum].Parse(GetType(TEnum), value), TEnum), Nothing)
        Return retValue
    End Function
    
    ' Populate ComboBox
    With ControlAnchorCB
        .Items.AddRange([Enum].GetNames(GetType(ContentAlignment)))
    End With
        
    ' Set combobox to value in My.Settings
    Dim ca As New ContentAlignment
    ControlAnchorCB.SelectedIndex = ControlAnchorCB.FindStringExact(My.Settings.ConnectorControlAnchor.ToString)

    ' To save value of combobox to My.Settings
    Dim ca As New ContentAlignment
    If TryParse(Of ContentAlignment)(ControlAnchorCB.SelectedItem, ca) Then My.Settings.ConnectorControlAnchor = ca

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 2010-09-20
    • 2011-03-28
    • 2015-02-12
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多