我可以在vb.net中的不同类中使用相同的变量定义吗?

时间:2016-07-26 14:57:38

标签: asp.net vb.net oop

是否可以在两个不同的类中使用相同的变量定义。 我刚刚开始学习vb.net,我正在尝试实现地址验证API,到目前为止, UPS类用于跟踪详细信息,但 UPSaddress 不能。两个类之间唯一不同的是路径变量和构造函数的参数。

Public Class UPS
 Private accessKey As String = "0D0F94260Dxxxxx"
 Private userName As String = "xxxxxx"
 Private passWord As String = "xxxxx"
 Private path As String = "https://www.ups.com/ups.app/xml/Track"
 Public xml As XmlDocument = New XmlDocument()



 public Sub New(trackNo As String)

    xml = getUPSXMLbyTrackingNumber(trackNo)
 End Sub




Public Function getIdentificationNumber() As String
    Dim idNo As String = getNodeValue(xml, "TrackResponse/Shipment/ShipmentIdentificationNumber")

    Return idNo.Trim
  End Function
End Class

这是另一个班级。

Public Class UPSAddress

Private accessKey As String = "0D0F94260Dxxxxx"
Private userName As String = "xxxxxxx"
Private passWord As String = "xxxxxxx"
Private path as String = "https://wwwcie.ups.com/ups.app/xml/XAV"
Public xml As XmlDocument = New XmlDocument()

public Sub New(Address As String,City as String,State as String,Zipcode as String)

    xml = getUPSXMLAddressValidation(Address,City,State,Zipcode)

End Sub

end class

这种做法是否正确?这就是我在VB编译器中调用类的方法

    Dim trackNo As String = upsTrackNo.Value
    Dim Address as String = upsAddress.value
    Dim City as String = upsCity.value
    Dim State as String = upsState.value
    Dim Zipcode as String = upsZipcode.value

    'This works'
    Dim ups As New UPS(trackNo){
    ..some code

    }

    'Im not sure if this will work'
    Dim upsAddress as new UPSAddress(Address,City,State,Zipcode){
    ...some code 
    }

1 个答案:

答案 0 :(得分:1)

通常,您可以使用包含公共变量的基类来执行此操作。然后,您的其他类继承此类并为path属性提供自己的实现:

Public MustInherit Class UPSBase
    Protected accessKey As String = "0D0F94260Dxxxxx"
    Protected userName As String = "xxxxxx"
    Protected passWord As String = "xxxxx"
    Protected MustOverride ReadOnly Property Path As String
End Class

Public Class UPSAddress
    Inherits UPSBase

    Protected Overrides ReadOnly Property Path As String
        Get
            Return "https://wwwcie.ups.com/ups.app/xml/XAV"
        End Get
    End Property
End Class

Public Class UPS
    Inherits UPSBase

    Protected Overrides ReadOnly Property Path As String
        Get
            Return "https://www.ups.com/ups.app/xml/Track"
        End Get
    End Property
End Class