简体   繁体   English

VB.Net结构具有预定义字符串列表中的变量

[英]VB.Net Structure with Variable from Predefined String List

The title probably isn't very accurate from a developer slang standpoint, but this is what I'm trying to achieve: 从开发人员语的角度来看,标题可能不太准确,但这就是我想要达到的目的:

I have a structure z with one variable x and upon creating an instance of the structure z, I want x to be constrained to a list of types of x... so zx = xType.1 or zx = xType.2 where xType 1 and 2 are strings and x is also a string when it comes down to it. 我有一个带有一个变量x的结构z,并且在创建结构z的实例时,我希望x被限制为x类型的列表...因此zx = xType.1或zx = xType.2其中xType 1和2是字符串,而x也是字符串。

Dim a As z
a.x = xType.1
Print(a.x)      'outputs "abc" because xType.1 = "abc"

EDIT 1: 编辑1:

Structure Z
    Dim X as String
End Structure

Sub Main()
    Dim a As Z
    a.X = "abc"
    Print(a.X) 'outputs "abc"
End Sub

This would be the simplest way where I can assign aX any value... I want to achieve something like this: 这是我可以为aX分配任何值的最简单方法...我想要实现以下目标:

Structure Z
    Dim X as ???
End Structure

Sub Main()
    Dim a As Z
    a.X = XType.abc
    Print(a.X) 'outputs "abc"
    a.X = XType.Zebra
    Print(a.X) 'outputs "Melons"
End Sub

So I have to make another structure or define those XTypes somewhere somehow. 因此,我必须以某种方式构造另一个结构或定义那些XType。

I think what you may be wanting to use is an enum. 我认为您可能想使用的是一个枚举。 You could do something like this: 您可以执行以下操作:

Structure Z
    Public Enum XType
        abc
        bcd
    End Enum
    Dim X As XType
End Structure

Sub Main()
    Dim a As Z
    a.X = Z.XType.abc
End Sub

This way you could create predefined values for X, and it would be similar to how a MsgBox has different MsgBoxStyles you can choose from. 这样,您可以为X创建预定义的值,这与MsgBox具有可以选择的不同MsgBoxStyles的方式类似。

EDIT: 编辑:

If you wanted to make it so that you didn't have to call ToString() to get the string value of X, you could try something like this (probably not the most effective, but it works): 如果您希望这样做,而不必调用ToString()来获取X的字符串值,则可以尝试这样的操作(可能不是最有效的方法,但是可以使用):

Structure Z
    Public Enum XType
        abc
        bcd
    End Enum
    Private Xt As XType
    Public Property X As Object
        Get
            Return Xt.ToString()
        End Get
        Set(ByVal value As Object)
            If value.GetType().Name = "XType" Then Xt = value
        End Set
    End Property
End Structure

Or you could have two properties like this: 或者您可以具有两个这样的属性:

Public X as XType
Public Property XString as String
    Get
        Return X.ToString()
    End Get
End Property

This link may also be helpful: http://msdn.microsoft.com/en-us/library/essfb559(v=vs.90).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1 该链接也可能会有所帮助: http : //msdn.microsoft.com/zh-cn/library/essfb559(v=vs.90).aspx?cs-save-lang=1&cs-lang=vb#code-snippet- 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM