Reflection on structure differs from class - but only in code

前端 未结 4 1851
执笔经年
执笔经年 2020-12-21 01:11

Code snippet:

Dim target As Object
\' target gets properly set to something of the desired type
Dim field As FieldInfo = target.GetType.GetField(\"fieldName\         


        
4条回答
  •  -上瘾入骨i
    2020-12-21 02:00

    The problem is that VB makes a copy of the object and the setvalue instruction applies to the copy, but not to the object itself. The workaround is to restore the changes to the original object through an auxliar var and the CType function. In the following example, we want to set the country field of the champion var to Spain (champion is a *St_WorldChampion* structure). We make the changes in the x var, an then we copy them to the champion var. It works.

    Public Structure St_WorldChampion
        Dim sport As String
        Dim country As String
    End Structure
    
    Sub UpdateWorldChampion()
        Dim champion As New St_WorldChampion, x As ValueType
        Dim prop As System.Reflection.FieldInfo
    
        ' Initial values: Germany was the winner in 2006
        champion.country = "Germany"
        champion.sport = "Football"
    
        ' Update the World Champion: Spain since 2010
        x = champion
        prop = x.GetType().GetField("country")
        prop.SetValue(x, "Spain")
        champion = CType(x, St_WorldChampion)
    
    End Sub
    

提交回复
热议问题