问题
Follow up to Direct access to full string representation of object.
I am trying to log the contents of an object to a text file. I can get the property-value pairs I want to log by executing this line in the immediate window:
?mDb.DatabaseOptions
{Microsoft.SqlServer.Management.Smo.DatabaseOptions}
AnsiNullDefault: False
...
UserData: Nothing
Unfortunately, I can't simply log mDb.DatabaseOptions.ToString
because that does not return any of the property-value pairs.
I tried to roll my own code using reflection. It works, but it returns way more information than I need. The debug.print
returns 33 property-value pairs, but the following code returns 95 property-value pairs.
For i As Integer = 0 To mDb.DatabaseOptions.Properties.Count - 1
WriteLine(mDb.DatabaseOptions.Properties(i).Name & ": " & _
mDb.DatabaseOptions.Properties(i).Value.ToString)
Next
What am I doing wrong?
回答1:
You are not using reflection, just the property "Properties" of your object. This aligns more closely to what Debug.Print does, I believe:
Public Sub WriteAsDebug(ByVal obj As Object)
For Each prop In obj.GetType.GetProperties()
WriteLine("{0}: {1}", prop.Name, prop.GetValue(obj, Nothing).ToString)
Next
End Sub
This method gets (by reflection) all the public properties defined in the object's type and writes the name of the property and the value (To String) in the specific object instance. A disclaimer, I am pretty sure this method fails awfully when trying to access indexed properties (propeties with parameters).
I am not sure that Debug.Print also reports only public members, if more members are needed check the BindingFlags options for the GetProperties method. You can also get more info on the PropertyInfo type that the method returns.
However, the Properties property you are using may give data not included in the properties of the class (which is what Debug.Print gives).
来源:https://stackoverflow.com/questions/8973859/using-reflection-to-mimic-debug-print-in-vb-net