3

我在 VB.net 中工作,我想创建一个通用的 ToString。有没有办法在“我”中做一个“为每个人”。

样本

 Public Property Var1() As String {... get ... set ...}
 Public Property Var2() As String {... get ... set ...}
 Public Property Var2() As String {... get ... set ...}

 Public Overrides Function ToString() As String
     dim str as stringbuilder
     for each item in Me
        str.append(item.tostring())
     next
     return str
 End Function

我的问题的原因是因为我的一些变量可以为空(无)。所以有了这样的泛型,我可以做到

if item isnot nothing then
    str.append(item.tostring())
end if

也许有更好的方法???

保护你

4

1 回答 1

1

这可以通过使用反射来实现GetFields。干得好:

Public Class [MyClass]
    Private a As String
    Private b As String

    Public Sub New(a As String, b As String)
        Me.a = a
        Me.b = b
    End Sub

    Public Overrides Function ToString() As String
        Dim sb = New StringBuilder()
        For Each item In [GetType]().GetFields(BindingFlags.NonPublic Or BindingFlags.Instance)
             sb.Append(item.Name) _
               .Append("=") _
               .Append(item.GetValue(Me)) _
               .Append(" ")
        Next
        Return sb.ToString()
    End Function

如果要显示属性,请使用GetProperties

于 2012-05-10T17:02:10.957 回答