Same property, different types

Say you have a class with the Uri property. Is there a way to get this property to accept both a string value and a Uri? How would you build it?

I would like to do something like one of the following, but none of them are supported (using VB, since it allows you to specify the type in the Set declaration for the second):

Class MyClass

    Private _link As Uri

   'Option 1: overloaded property
    Public Property Link1 As Uri
        Get
            return _link
        End Get
        Set(ByVal value As Uri)
           _link = value
        End Set
    End Property

    Public Property link1 As String
        Get
            return _link.ToString()
        End Get
        Set(Byval value As String)
           _link = new Uri(value)
        End Set
   End Property

   ' Option 2: Overloaded setter
   Public Property link2 As Uri
      Get
          return _link
      End Get
      Set(Byval value As Uri)
          _link = value
      End Set
      Set(Byval value As String)
          _link = new Uri(value)
      End Set
End Class

Given that they probably won't be supported anytime soon, how else can you handle this? I'm looking for something a little nicer than just providing an extra method .SetLink(string value), and I'm still on .Net2.0 (although if later versions have a nice opportunity for this, I'd love to hear about that).

, ​​: SqlConnection, , , .

+3
4

, , :

Public WriteOnly Property UriString() As String
    Set(ByVal value As String)
        m_Uri = new Uri(value)
    End Set
End Property

, WriteOnly, .

+3

,

Public Sub SetLink(ByVal value as String)
    _link = new Uri(value)
End Sub

, AFAIK.

+3

, Uri. , , Uri?

, , , .NET.

I would use the method Uriexclusively and perhaps create a convenienec method to set the property Urispecified by the string. However, since converting from Stringto Uriis simple, even this may be unnecessary.

+1
source

You cannot have such a property, but you can create two properties that control the same main field - exactly the same as Height / Width / Size in Windows Forms.

+1
source

Source: https://habr.com/ru/post/1697820/


All Articles