不保留对自定义类中的属性值所做的更改

时间:2011-06-10 21:20:44

标签: vb.net reflection

我创建了这个函数来从自定义类中的属性值中删除vbCrLf:(vTransaction)

Public Function ValidateTransaction(ByRef vTransaction)            
        Dim property1 As String
        Dim value1 As String

        For Each p As System.Reflection.PropertyInfo In vTransaction.GetType().GetProperties()
            If p.CanRead Then
                property1 = p.Name '// FOR TESTING to identify Property Name
                value1 = p.GetValue(vTransaction, Nothing)
                If (TypeOf value1 Is String) Then
                    If value1 <> " " And value1 <> "" Then
                        'MsgBox("Before .Replace:" & vbNewLine & value1.ToString) '// FOR TESTING.
                        value1 = value1.ToString.Replace(vbCrLf, " ")
                        'MsgBox("After .Replace:" & vbNewLine & value1.ToString) '// FOR TESTING.
                    End If
                End If
            End If
        Next

        Return vTransaction

    End Function

在整个测试中,我可以验证vbCrLf是否正在按预期替换为空格。当我重新检查vTransaction时,没有保留更改,并且vbCrlf仍在那里。

我需要做些什么来保留对vTransaction中的值所做的更改。

1 个答案:

答案 0 :(得分:4)

您没有再次设置属性值。您只是创建一个之后未使用的字符串。你最内层的If-block应该是这样的:

If value1 <> " " And value1 <> "" Then
    'MsgBox("Before .Replace:" & vbNewLine & value1.ToString) '// FOR TESTING.
    p.SetValue(vTransaction, value1.ToString.Replace(vbCrLf, " "), Nothing)
    'MsgBox("After .Replace:" & vbNewLine & value1.ToString) '// FOR TESTING.
End If