在VB.Net中使用反射模拟Debug.Print [英] Using reflection to mimic Debug.Print in VB.Net

查看:24
本文介绍了在VB.Net中使用反射模拟Debug.Print的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟进直接访问对象的完整字符串表示.

我正在尝试将对象的内容记录到文本文件中.我可以通过在立即窗口中执行这一行来获取我想要记录的属性-值对:

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

不幸的是,我不能简单地记录 mDb.DatabaseOptions.ToString 因为这不会返回任何属性值对.

Unfortunately, I can't simply log mDb.DatabaseOptions.ToString because that does not return any of the property-value pairs.

我尝试使用反射来滚动我自己的代码.它有效,但它返回的信息比我需要的要多.debug.print 返回 33 个属性值对,但以下代码返回 95 个属性值对.

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

我做错了什么?

推荐答案

您没有使用反射,只是使用了对象的属性属性".我相信这与 Debug.Print 的作用更接近:

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

此方法获取(通过反射)对象类型中定义的所有公共属性,并在特定对象实例中写入属性名称和值(To String).免责声明,我很确定此方法在尝试访问索引属性(带参数的属性)时会失败.

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).

我不确定 Debug.Print 是否也只报告公共成员,如果需要更多成员,请检查 GetProperties 方法.您还可以获取有关 PropertyInfo 类型的更多信息方法返回.

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.

但是,您正在使用的 Properties 属性可能会提供不包含在类属性中的数据(这是 Debug.Print 提供的).

However, the Properties property you are using may give data not included in the properties of the class (which is what Debug.Print gives).

这篇关于在VB.Net中使用反射模拟Debug.Print的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆