Vb.net .net-将类用作一个参数

Vb.net .net-将类用作一个参数,vb.net,class,properties,parameters,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 St

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

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 .......
有办法吗


我并不是真的把值写在文本框中,但这只是一个简单的例子。

我想你想要的是一个属性。您需要向类中添加一个属性,如:

Public Property Combination() As String
    Get
        Return a & b & c & d & e ...
    End Get
End Property
然后获取您要使用的值

Textbox1.text = test.combination

(有关更多详细信息,请参见)

我建议您覆盖内置的
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

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

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
来设置属性的值。但是,反射效率很低,如果使用不当,可能会导致代码脆弱。因此,作为一般规则,只要有其他更好的方法来做同样的事情,就应该避免使用反射。换句话说,您通常应该将反射保存为最后手段

如果没有更多的细节,很难确定在您的特定情况下还有哪些其他选项可以很好地工作,但我强烈怀疑更好的解决方案是使用
列表
字典
,例如:

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
或:


不能将其作为参数传递给方法吗?例如:
Public Sub-SomeMethod(t As test)
,您可以重写类的ToString方法,以便在一次调用中根据需要显示或以其他方式从属性返回数据。此类的具体用途是什么?您可能有一个设计问题。@我使用它来存储变量的值,因此我不必每次都将它们作为参数传递。这当然会使获取所有值变得更容易,但会使通过代码设置值变得更困难。您仍然可以按正常方式使用属性a、b、c、d等。这只是一个额外的财产以及你的其他财产,每次你调用它,你会得到你的其他财产的最新组合。或者我误解了什么?如果你在类中添加更多的属性x,y,z,你只需要在一个地方修改属性。
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