【问题标题】:Enum with option to show up second describtion带有显示第二个描述的选项的枚举
【发布时间】:2015-06-23 18:15:10
【问题描述】:

我的代码中有一些枚举(如下),我正在使用这个枚举来显示名称,例如:Datasource.Some_server1.ToString()。如果特定的服务器枚举是,我在代码引擎中使用它来进行一些计算,并在网页上显示名称。现在的问题是我的经理让我显示不同的名字。因此,例如不是 Some_server1,而是:HHGT Server 56。问题是我的代码正在使用这些枚举名称来执行某些任务,而我不能只在此枚举中更改它。你知道我可以在我的项目中知道的某种方式吗现在我想看到这个枚举的描述名称所以不是 Some_server1 但现在如果 Datasource.Some_server1.ToString() 然后显示 HHGT Server 56。是否有这种可能性而不改变我的枚举其余代码的方式仍在使用它吗?希望你明白我的意思。

Public Enum Datasource
    Some_server1
    Some_server2
    Some_server3
    Some_server4
End Enum

【问题讨论】:

标签: vb.net


【解决方案1】:

您可以通过为每个成员分配Description Attribute 来为您的枚举添加更多上下文。

Public Enum DataSource
    <Description("HHGT Server 56")> Some_server1
    'etcetera
End Enum

然后你可以使用这个函数(取自a really useful extension)来获取描述字符串:

Public Shared Function GetEnumDescription(ByVal value As [Enum]) As String
    Dim fi As Reflection.FieldInfo = value.[GetType]().GetField(value.ToString())
    Dim attributes As DescriptionAttribute() = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
    Return If((attributes.Length > 0), attributes(0).Description, value.ToString())
End Function

【讨论】:

  • 另见dbasnett's link 一个非常相似的例子。 ...总有人在抽签上比我快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2019-12-18
  • 2015-10-09
相关资源
最近更新 更多