.net - 使用Class作为一个参数

时间:2014-02-25 15:19:19

标签: vb.net class properties parameters

我有一个有几个属性的类。

Public Class test
    Public Property a As String
    Public Property b As String
    Public Property c As String
    Public Property d As String
    Public Property e As String
    Public Property f As String
    Public Property g As String
End Class

在我的VB.net代码中,我正在为每个属性分配一个值。

我想将整个测试类作为一个参数发送,并使用其中的所有值。

因此,如果我稍后添加额外的参数,我希望它们可以动态使用,而不是每次都写这个:

Textbox1.text= test.a & test.b & test.c .......

有什么办法吗?

我没有真正在文本框中写入值,但这只是一个简化的示例。

3 个答案:

答案 0 :(得分:1)

我认为你想要的是财产。您需要在类中添加属性,如:

Public Property Combination() As String
    Get
        Return a & b & c & d & e ...
    End Get
End Property

然后获取您使用的值

Textbox1.text = test.combination

(有关详细信息,请参阅http://www.dotnetperls.com/property-vbnet

答案 1 :(得分:0)

我建议您覆盖内置的ToString功能。另外,为了进一步简化此操作,请添加CType运算符。

Public Class test

    Public Property a As String
    Public Property b As String
    Public Property c As String
    Public Property d As String
    Public Property e As String
    Public Property f As String
    Public Property g As String

    Public Shared Widening Operator CType(obj As test) As String
        Return If((obj Is Nothing), Nothing, obj.ToString())
    End Operator

    Public Overrides Function ToString() As String
        Return String.Concat(Me.a, Me.b, Me.c, Me.d, Me.e, Me.f, Me.g)
    End Function

End Class

你可以这么做:

Textbox1.text = test

答案 2 :(得分:0)

有一种方法可以动态获取和设置任何对象的属性值。 .NET中的此类功能统称为 Reflection 。例如,要遍历对象中的所有属性,您可以执行以下操作:

Public Function GetPropertyValues(o As Object) As String
    Dim builder As New StringBuilder()
    For Each i As PropertyInfo In o.GetType().GetProperties
        Dim value As Object = Nothing
        If i.CanRead Then
            value = i.GetValue(o)
        End If
        If value IsNot Nothing Then
            builder.Append(value.ToString())
        End If
    Next
    Return builder.ToString()
End Function

在上面的示例中,它调用i.GetValue来获取属性的值,但您也可以调用i.SetValue来设置属性的值。但是,反射效率低下,如果使用不当,可能会导致代码变得脆弱。因此,作为一般规则,只要有任何其他更好的方法来做同样的事情,你应该避免使用反射。换句话说,您通常应该将反射保存为最后的手段。

如果没有更多细节,很难确定其他选项在您的特定情况下会有什么效果,但我强烈怀疑更好的解决方案是使用ListDictionary,实例:

Dim myList As New List(Of String)()
myList.Add("first")
myList.Add("second")
myList.Add("third")
' ...
For Each i As String In myList
    Textbox1.Text &= i
Next

或者:

Dim myDictionary As New Dictionary(Of String, String)()
myDictionary("a") = "first"
myDictionary("b") = "first"
myDictionary("c") = "first"
' ...
For Each i As KeyValuePair(Of String, String) In myDictionary
    Textbox1.Text &= i.Value
Next