获取字段运算符



>我正在使用一个函数从列表中获取字段数据。我需要知道 .GetFields 运算符将只返回字段,或者它是否会实际使用存储在那里的数据填充它们?在阅读 msdn 后,我认为是后者,但我不知道,而且我在:(之前从未使用这些"测试方法"。任何帮助不胜感激!(或者即使你能告诉我如何做一个测试方法也会有所帮助!这是代码:

   ''' <summary>
''' This function will return all of the fields for a certain class as well as the data stored in them
''' </summary>
''' <param name="list"></param>
''' <returns></returns>
Public Shared Function GetFieldData(ByVal list As IList(Of Object)) As FieldInfo()
    Dim fields() As FieldInfo = list.Single.GetType().GetFields()
    Return fields
End Function

结束类

这是用于创建新项的代码

  ''' <summary>
''' This function will create new Before and After objects
''' everything should be passed in as a IEnum
''' </summary>
''' <param name="Before"></param>
''' <param name="After"></param>
''' <returns></returns>
Function NewItem(Before As IEnumerable(Of Object), After As IEnumerable(Of Object))
    If (Not ObjectsAreSameClass(Before, After)) Then    'If object classes are not the same, send an error message, else continue 
        'Pop error
    Else
        Dim BeforeFields() As FieldInfo = GetFieldData(Before)
        Dim AfterFields() As FieldInfo = GetFieldData(After)
        ObjectCounter += 1
        'Now check and make sure the objects are not the same
        If (BeforeFields.Equals(AfterFields)) Then
            'Objects are the same so pop error?
        End If
    End If
    Return Nothing
End Function

FieldInfo是有关字段的信息,不包括其值。若要获取该值,必须提供该对象类型的实例。下面是一个示例,您可以将其放置在窗体上以查看其工作原理:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim info() As FieldInfo = GetType(Form).GetFields(BindingFlags.NonPublic Or 
                                                      BindingFlags.Instance)
    For Each item As FieldInfo In info
        Dim value As Object = item.GetValue(Me) ' Get the value from 'Me'
        If Not IsNothing(value) Then
            Debug.Print("{0} = {1}", item.Name, value.ToString())
        Else
            Debug.Print("{0} = Nothing", item.Name)
        End If
    Next
End Sub

相关内容

最新更新