gpt4 book ai didi

.net - 如何存储枚举值的字符串描述?

转载 作者:行者123 更新时间:2023-12-02 20:33:45 25 4
gpt4 key购买 nike

我正在开发的应用程序有很多枚举。

这些值通常是从应用程序的下拉列表中选择的。

存储这些值的字符串描述的普遍接受的方式是什么?

这是当前的问题:

Public Enum MyEnum
SomeValue = 1
AnotherValue = 2
ObsoleteValue = 3
YetAnotherValue = 4
End Enum

下拉列表应包含以下选项:

Some Value
Another Value
Yet Another Value (Minor Description)

并非所有枚举都适合枚举名称(其中一个的次要描述只是一个示例),并且并非所有枚举值都是当前值。有些保留只是为了向后兼容和显示目的(即打印输出,而不是表单)。

这会导致以下代码情况:

For index As Integer = 0 To StatusDescriptions.GetUpperBound(0)
' Only display relevant statuses.
If Array.IndexOf(CurrentStatuses, index) >= 0 Then
.Items.Add(New ExtendedListViewItem(StatusDescriptions(index), index))
End If
Next

这似乎可以做得更好,但我不确定如何做。

最佳答案

您可以使用Description属性(C# 代码,但应该翻译):

public enum XmlValidationResult
{
[Description("Success.")]
Success,
[Description("Could not load file.")]
FileLoadError,
[Description("Could not load schema.")]
SchemaLoadError,
[Description("Form XML did not pass schema validation.")]
SchemaError
}

private string GetEnumDescription(Enum value)
{
// Get the Description attribute value for the enum value
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);

if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}

Source

关于.net - 如何存储枚举值的字符串描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3188466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com