3

Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri? How would you build it?

I'd like to be able to do something like one of the following, but neither are supported (using VB, since it lets you specify type in the Set declaration for the 2nd one):

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 those probably won't be supported any time soon, how else would you handle this? I'm looking for something a little nicer than just providing an additional .SetLink(string value) method, and I'm still on .Net2.0 (though if later versions have a nice feature for this, I'd like to hear about it).

I can think of other scenarios where you might want to provide this kind of overload: a class with an SqlConnection member that lets you set either a new connection or a new connection string, for example.

4

4 に答える 4

3

I think you just need to provide an accompanying

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

Nothing nicer is available, AFAIK.

于 2008-10-02T15:11:32.673 に答える
3

または、もちろん、オーバーロードを控えて、プロパティに適切な名前を付けることもできます。

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

もちろん、これを作成する必要はありませんが、WriteOnly適切なようです。

于 2008-10-02T15:14:57.843 に答える
1

Uri プロパティを持つクラスがあるとします。そのプロパティを取得して、文字列値と Uri の両方を受け入れる方法はありますか?

これは、戻り値の型だけが異なる 2 つのゲッターを持つことを意味し、これは .NET では許可されていないためです。

このメソッドを排他的に使用し、文字列を指定してプロパティUriを設定するための便利なメソッドをおそらく作成します。URIただし、 から への変換StringURI簡単なので、これも不要かもしれません。

于 2008-10-02T15:12:25.790 に答える
1

そのようなプロパティを 1 つ持つことはできませんが、Windows フォームの高さ/幅/サイズのように、両方とも同じ基本フィールドを操作する 2 つのプロパティを作成できます。

于 2008-10-02T15:13:18.080 に答える