string 在VB.Net中定义字符串ENUM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12312325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Define String ENUM in VB.Net
提问by Brijesh Patel
I am using Window Application for my project. There is situation where i need to define string enum and using it in my project.
我正在为我的项目使用窗口应用程序。在某些情况下,我需要定义字符串枚举并在我的项目中使用它。
i.e.
IE
Dim PersonalInfo As String = "Personal Info"
Dim Contanct As String = "Personal Contanct"
Public Enum Test
PersonalInfo
Contanct
End Enum
Now i want value of that variable PersonalInfo and Contract as "Personal Info" and "Personal Contanct".
现在我想要那个变量 PersonalInfo 和 Contract 的值是“Personal Info”和“Personal Contanct”。
How can i get this value using ENUM? or anyother way to do it.
如何使用 ENUM 获取此值?或任何其他方式来做到这一点。
Thanks in advance...
提前致谢...
采纳答案by sloth
You could just create a new type
你可以创建一个新类型
''' <completionlist cref="Test"/>
Class Test
Private Key As String
Public Shared ReadOnly Contact As Test = New Test("Personal Contanct")
Public Shared ReadOnly PersonalInfo As Test = New Test("Personal Info")
Private Sub New(key as String)
Me.Key = key
End Sub
Public Overrides Function ToString() As String
Return Me.Key
End Function
End Class
and when you use it, it kinda lookslike an enum:
当你使用它,它还挺看起来像一个枚举:
Sub Main
DoSomething(Test.Contact)
DoSomething(Test.PersonalInfo)
End Sub
Sub DoSomething(test As Test)
Console.WriteLine(test.ToString())
End Sub
output:
输出:
Personal Contanct
Personal Info
个人联系方式
个人信息
回答by Slai
For non-integer values, Const
in a Structure
(or Class
) can be used instead:
对于非整数值,可以使用Const
in Structure
(or Class
) 代替:
Structure Test
Const PersonalInfo = "Personal Info"
Const Contanct = "Personal Contanct"
End Structure
or in a Module
for direct access without the Test.
part:
或在Module
没有Test.
部分的情况下直接访问:
Module Test
Public Const PersonalInfo = "Personal Info"
Public Const Contanct = "Personal Contanct"
End Module
In some cases, the variable name can be used as a value:
在某些情况下,变量名可以用作值:
Enum Test
Personal_Info
Personal_Contanct
End Enum
Dim PersonalInfo As String = Test.Personal_Info.ToString.Replace("_"c, " "c)
' or in Visual Studio 2015 and newer:
Dim Contanct As String = NameOf(Test.Personal_Contanct).Replace("_"c, " "c)
回答by Denis
How about using Tagging. Something like:
如何使用标记。就像是:
Public Enum MyEnum
<StringValue("Personal Contact")>Contact
<StringValue("My PersonalInfo")>PersonalInfo
End Enum
You would have to write the StringValue attribute as:
您必须将 StringValue 属性编写为:
Public Class StringValueAttribute
Inherits Attribute
Public Property Value As String
Public Sub New(ByVal val As String)
Value = val
End Sub
End Class
To get it out:
把它弄出来:
Public Function GetEnumByStringValueAttribute(value As String, enumType As Type) As Object
For Each val As [Enum] In [Enum].GetValues(enumType)
Dim fi As FieldInfo = enumType.GetField(val.ToString())
Dim attributes As StringValueAttribute() = DirectCast(fi.GetCustomAttributes(GetType(StringValueAttribute), False), StringValueAttribute())
Dim attr As StringValueAttribute = attributes(0)
If attr.Value = value Then
Return val
End If
Next
Throw New ArgumentException("The value '" & value & "' is not supported.")
End Function
Public Function GetEnumByStringValueAttribute(Of YourEnumType)(value As String) As YourEnumType
Return CType(GetEnumByStringValueAttribute(value, GetType(YourEnumType)), YourEnumType)
End Function
And then a call to get the Enum (using string attribute):
然后调用获取枚举(使用字符串属性):
Dim mEnum as MyEnum = GetEnumByStringValueAttribute(Of MyEnum)("Personal Contact")
To get the "Attribute" value out (removed handling 'Nothing' for clarity):
要获取“属性”值(为清楚起见,删除了“无”处理):
Public Function GetEnumValue(Of YourEnumType)(p As YourEnumType) As String
Return DirectCast(Attribute.GetCustomAttribute(ForValue(p), GetType(StringValueAttribute)), StringValueAttribute).Value
End Function
Private Function ForValue(Of YourEnumType)(p As YourEnumType) As MemberInfo
Return GetType(YourEnumType).GetField([Enum].GetName(GetType(YourEnumType), p))
End Function
And the call to get the string attribute (using Enum):
以及获取字符串属性的调用(使用枚举):
Dim strValue as String = GetEnumValue(Of MyEnum)(MyEnum.Contact)
回答by Jon Skeet
How can i get this value using ENUM? or anyother way to do it.
如何使用 ENUM 获取此值?或任何其他方式来做到这一点。
There are three common ways of mapping enum values to strings:
将枚举值映射到字符串的常用方法有以下三种:
- Use a
Dictionary(Of YourEnumType, String)
- Decorate the enum values with attributes (e.g.
DescriptionAttribute
) and fetch them with reflection - Use a
Switch
statement
- 用一个
Dictionary(Of YourEnumType, String)
- 用属性(例如
DescriptionAttribute
)装饰枚举值并用反射获取它们 - 使用
Switch
声明
The first of these options is probably the simplest, in my view.
在我看来,这些选项中的第一个可能是最简单的。
回答by Rob Heijligers
I know this is an old post put I found a nice solution that worth sharing:
我知道这是一篇旧帖子,我找到了一个值得分享的不错的解决方案:
''' <summary>
''' Gives acces to strings paths that are used often in the application
''' </summary>
Public NotInheritable Class Link
Public Const lrAutoSpeed As String = "scVirtualMaster<.lrAutoSpeed>"
Public Const eSimpleStatus As String = "scMachineControl<.eSimpleStatus>"
Public Const xLivebitHMI As String = "scMachineControl<.xLivebitHMI>"
Public Const xChangeCycleActive As String = "scMachineControl<.xChangeCycleActive>"
End Class
Usage:
用法:
'Can be anywhere in you applicaiton:
Link.xChangeCycleActive
This prevents unwanted extra coding, it's easy to maintain and I think this minimizes extra processor overhead.
这可以防止不必要的额外编码,易于维护,我认为这可以最大限度地减少额外的处理器开销。
Also visual studio shows the string attributes right after you type "Link" just like if it is a regular Enum
此外,visual studio 在您键入“Link”后立即显示字符串属性,就像它是常规 Enum 一样
回答by SteveCinq
If all you want to do is display the enums in a list or combo, you can use tagging such as
如果您只想在列表或组合中显示枚举,则可以使用标记,例如
Private Enum MyEnum
Select_an_option___
__ACCOUNTS__
Invoices0
Review_Invoice
__MEETINGS__
Scheduled_Meetings0
Open_Meeting
Cancelled_Meetings0
Current_Meetings0
End Enum
Then pull the MyEnum
into a string and use Replace
(or Regex
) to replace the tags: "___" with "...", "__" with "**", "_" with " ", and remove trailing numbers. Then repack it up into an array and dump it into a combobox which will look like:
然后将其拉MyEnum
入字符串并使用Replace
(或Regex
)替换标签:“___”替换为“...”,“__”替换为“**”,“_”替换为“”,并删除尾随数字。然后将其重新打包成一个数组并将其转储到一个组合框,如下所示:
Select an option...
**ACCOUNTS**
Invoices
Review Invoice
**MEETINGS**
Scheduled Meetings
Open Meeting
Cancelled Meetings
Current Meetings
(You can use the numbers to, say, disable a text field for inputting an invoice number or meeting room. In the example, Review Invoice
and Open Meeting
might be expecting additional input so a text box might be enabled for those selections.)
(例如,您可以使用这些数字来禁用用于输入发票编号或会议室的文本字段。在示例中,Review Invoice
并且Open Meeting
可能需要额外的输入,因此可以为这些选择启用文本框。)
When you parse the selected combo item, the enumeration will work as expected but you only really need to add a single line of code - the text replacement - to get the combo to look as you wish.
当您解析选定的组合项时,枚举将按预期工作,但您只需要添加一行代码 - 文本替换 - 让组合看起来如您所愿。
(The explanation is about 10 times as involved as the actual solution!)
(解释大约是实际解决方案的 10 倍!)