开发者

Why can't define get type and set type distinctly within Properties?

Here is the problem, I wanted to开发者_开发问答 define a property which accepts decimal numbers and do some process on the value and return string such as the below:

Public Property Amount() As String
    Get
        Return Utility.PaddingRight(Me.msAmount.ToString(), 10)
    End Get
    Set(ByVal vsValue As Decimal)
        Me.msAmount = vsValue
    End Set
End Property

But compilers warns "Set parameters must have the same type of the containing property."

It doesn't look like it should throws an error since it looks legit.


The reason that you can't is because what you put into a property should be exactly the same as what you get out of it. If the type changed then this condition would never be true. Microsoft's spec says that "Properties are like smart fields". Imagine if a field (class variable) changed between reading and writing.

Your goal is completely valid but that's not the intended use for properties. (By "intended goal" I mean Microsoft's intended goal.) Your design would also opens doors for potential problems if an invalid or null string were passed in. One of the design goals for properties is that they are light weight and shouldn't throw errors. They can but shouldn't. The recommended solution is to use the TryParse pattern for your property.

EDIT

Sorry, my brain was sidetracked, your goal is changing the getter, not the setter. The pattern that you're looking for is just a read-only property (as @msarchet pointed out) that's specific to your getter. For instance, AmountForPrint or something. You should still include a read/write for your actual value, too.

Public ReadOnly Property AmountForPrint
    Get
        Return Me.Amount.ToString()
    End Get
End Property
Public Property Amount As Integer
    Get

    End Get
    Set(value As Integer)

    End Set
End Property


I think you need a to do this with a method not a property

Public Function Amount(ByVal value As Decimal) As String

End Function


This is just a shot in the dark . . .

Set(ByVal vsValue As String)
    Me.msAmount = System.Convert.ToDecimal(vsValue)
End Set


You'd be far better off doing this as such

Public Read Only Property Amount() As String
    Get
         Return Utility.PaddingRight(Me.msAmount.ToString(), 10)
    End Get
End Property

Public Sub SetAmount(ByVal value As Decimal)
    Me.msAmount = value
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜