Public Function GenerateHeader(ByVal FrameNumber As String) As String
Dim HeaderRecord As String = FrameNumber
Try
For Each P As System.Reflection.PropertyInfo In Me.GetType().GetProperties()
If P.CanRead Then
If P.GetValue( Me, Nothing)Is Nothing Then 'get value of me.
HeaderRecord += "|"
Else
HeaderRecord += P.GetValue(Me, Nothing).ToString & "|"
End If
End If
Next
Return HeaderRecord
Catch ex As Exception
LogError("ASTMHeader", "GenerateHeader", Err.Erl, Err.Description, "")
Return HeaderRecord
End Try
End Function
这是一段非常糟糕的代码。我不知道你从哪儿弄来的,但它需要重写。
我已经为您添加了注释到代码中,但基本上这段代码使用反射来获取函数嵌入的类的所有属性。然后,它使用反射来尝试读取当前对象的每个属性的值,并将它们作为管道分隔的字符串返回。如果我不得不猜测,有人试图将值存储到数据库或文件中,并在以后恢复它们。这是一种糟糕的做事方式。通常,您需要将对象序列化和反序列化为JSON或XML来实现这一点。
Public Function GenerateHeader(ByVal FrameNumber As String) As String
Dim HeaderRecord As String = FrameNumber
Try
' Use reflection to get all of the properties on the class this function is a part of
' Loop them
For Each P As System.Reflection.PropertyInfo In Me.GetType().GetProperties()
' Check to see if this is a readable property
If P.CanRead Then
' P.GetValue(obj As Object, index As Object())
' Is the value of the property Nothing (i.e. not set) then just add a | to the result
If P.GetValue(Me, Nothing) Is Nothing Then 'get value of me.
HeaderRecord += "|"
Else
' Otherwise add the Value, coverted to a string, to the result followed by a |
HeaderRecord += P.GetValue(Me, Nothing).ToString & "|"
End If
End If
Next
Return HeaderRecord
Catch ex As Exception
' Trying to read the values of some properties may cause e crash (e.g. trying to read
' the IsValid property of an ASP.NET page before validation has taken place)
' Log the error and just return everything we have so far
Return HeaderRecord
End Try
End Function