0

We had the need to create the following object, basically a way to pass in integer or strings and fetch these back out as either an integer or a zero-padded string:

Public Class DOC_NUMBER
    Private m_DOC_NUMBER As Integer = 0

    Public Sub New(ByVal DOC_NUMBER As Integer)
        m_DOC_NUMBER = DOC_NUMBER
    End Sub

    Public Sub New(ByVal DEPOT_CODE As String)
        Dim ParseInput As Integer = 0
        If Integer.TryParse(DEPOT_CODE, ParseInput) = False Then
            m_DOC_NUMBER = 0
        Else
            m_DOC_NUMBER = ParseInput
        End If
    End Sub

    Public Overrides Function ToString() As String
        Return Right("0000000000" & m_DOC_NUMBER.ToString(), 10)
    End Function

    Public Function ToInteger() As Integer
        Return m_DOC_NUMBER
    End Function
End Class

An instance of this class can then be set as follows:

Dim DocumentID As New DOC_NUMBER("00123")
Dim DocumentID As New DOC_NUMBER(123)

This can then be assigned to other vars like this:

Dim NewDocumentID as Integer = DocumentID.ToInteger()
Dim NewDocumentID as String = DocumentID.ToString()

99% of the time however we'll be dealing with integers, so we'd like to make the .ToInteger() optional, for example:

Dim NewDocumentID as Integer = DocumentID

Obviously this currently gives the error "Value of type 'X.DOC_NUMBER' cannot be converted to 'Integer'"

How do we modify the class to automatically pass out an integer it's being assigned to an integer?

Examples in any .net language will be fine.

4

1 回答 1

4

你可以用隐式转换做你想做的事。在 C# 中可能如下所示:

public static implicit operator string(DOC_NUMBER docNum)
{
    // implement
}
public static implicit operator int(DOC_NUMBER docNum)
{
    // implement
}

VB.NET 等价物是Widening Operator.

但是,我会指出,我发现ToInteger()and ToString()(或作为属性:AsIntegerand AsString,也许)比隐式转换更清晰、更简单,因此也更好。

于 2013-08-01T15:08:16.633 回答