Is there a way to Overload a Property in .NET

拈花ヽ惹草 提交于 2019-11-30 17:34:11

To overload something--method or property--you need for it to accept a different set of parameters. Since properties in VB.NET can accept parameters, I guess you can overload them; but they have to be different.

So you could do this:

Public Overloads Readonly Property Average() As Double
Public Overloads Readonly Property Average(ByVal startIndex As Integer) As Double

But not this:

Public Overloads Readonly Property Average() As Double
Public Overloads Readonly Property Average() As Decimal

This should not be possible. You are effectively trying to make a property that could return two different types. There is no way for the system to make the determination as to what you are trying to call.

You will have to give unique property names to each.

Your signatures are the same (only the return types differ). the compiler will not know which method you're calling. That is your problem. Change the signatures.

have you tried using a class based on an interface? Then, you could have different classes based on the same common interface and the property associated to the interface type, not the specific class itself.

There is one way

Public Enum myType
    inInteger = 0
    inDouble = 1
    inString = 2
End Enum

Public Class clsTest
Dim _Value1 As Integer
Dim _Value2 As Double
Dim _Value3 As String

Public Property MyValue(ByVal Typ As myType) As Object
    Get
        Select Case Typ
            Case myType.inDouble
                Return _Value2
            Case myType.inInteger
                Return _Value1
            Case Else
                Return _Value3
        End Select
    End Get
    Set(ByVal value As Object)
        Select Case Typ
            Case myType.inDouble
                _Value2 = value
            Case myType.inInteger
                _Value1 = value
            Case Else
                _Value3 = value
        End Select
    End Set
End Property
End Class

It is not possible to overload properties. That being said, you could accomplish what you want by creating implicit conversions or overloading the = operator.

It would be possible to have the property operate on some special class, which supports widening conversion operators to and from the real types of interest. In some circumstances this could work reasonably well and provide a useful expansion. The biggest limitations:

  1. If the special class/struct gets converted to type Object, it won't behave like the thing to which it's supposed to be typecast.
  2. If the special thing is a class, then every time the property is get or set will require the instantiation of a new garbage-collected object.

Still, in some circumstances this may be a useful abstraction (especially if the base type would be a struct).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!