简体   繁体   English

变量类成员分配

[英]Variable class member assignment

I am working in vb.net and I am wondering if there is any way to use a variable string for member assignment of a class.. The field to be compared is represented by an integer value, and based off of an enumeration I want to compare the field represented by that integer. 我正在vb.net中工作,我想知道是否有任何方法可以使用变量字符串进行类的成员分配。.要比较的字段由整数值表示,并且基于我想要的枚举比较该整数表示的字段。 For example, here is the basic idea of what I am trying to accomplish. 例如,这是我要完成的基本想法。

Public Class Point
   Public X As Double
   Public Y As Double
   Public Z As Double
End Class


Public Enum PointEnum As Short
   X = 0
   Y = 1
   Z = 2
End Enum

With a list of Points, I want to be able to compare x, y, or z depending on 'enumValue' that is passed into the program. 通过一个点列表,我希望能够根据传递到程序中的“ enumValue”来比较x,y或z。

Dim PointList As New List(Of Point)
If PointList(0).[Enum].GetName(GetType(PointEnum), enumValue) < someValue Then
   ...
End If

The PointList(0).[Enum].GetName(GetType(PointEnum), enumValue) is the line I am having trouble with.. If my actual code were as simple as having x, y, and z I would just use a select case or if statements, however the class I am using has over 30 properties. PointList(0).[Enum].GetName(GetType(PointEnum), enumValue)是我遇到的问题。如果我的实际代码像具有x,y和z一样简单,则只需使用select case或if语句,但是我正在使用的类具有30多个属性。 Thanks in advance for any recommendations or solutions 预先感谢您的任何建议或解决方案

If all the fields in the classes are PUBLIC as shown, then you can use the legacy CallByName() function, which makes it really easy to write/read: 如果类中的所有字段均为所示的PUBLIC ,则可以使用旧式CallByName()函数,这实际上使编写/读取非常容易:

    Dim PointList As New List(Of Point)
    PointList.Add(New Point() With {.X = 1.0, .Y = 2.0, .Z = 3.0})
    PointList.Add(New Point() With {.X = 3.0, .Y = 6.0, .Z = 9.0})
    PointList.Add(New Point() With {.X = 4.0, .Y = 8.0, .Z = 12.0})

    Dim enumValue As PointEnum = PointEnum.Z
    Dim someValue As Double = 5

    If CallByName(PointList(0), enumValue.ToString, CallType.Get) < someValue Then
        Debug.Print("Less Than")
    Else
        Debug.Print("Not Less Than")
    End If

If you'd really like to use Reflection, or if the fields are not Public, then I have a similar example here . 如果您真的想使用Reflection,或者如果字段不是Public,那么这里有一个类似的示例。

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

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