同一属性,不同类型的 [英] Same property, different types

查看:121
本文介绍了同一属性,不同类型的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说你有一类与URI属性。有没有办法让这个属性接受两个字符串值和一个URI?你将如何打造呢?

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?

我希望能像做了以下情况之一,但也都支持(使用VB,因为它可以让你在设置声明中指定类型:第二个):

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

鉴于这些可能不会支持任何时间很快,怎么回事,你会处理这个问题?我在寻找不只是提供了一个额外的 .SetLink(字符串值)法的东西更好一点,我仍然在.Net2.0(不过,如果更高版本有这个一个不错的功能,我想听到的话)。

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).

我能想到的其他情况下,您可能要提供这种过载:一类与SqlConnection的成员,让你无论是设置新的连接或一个新的连接字符串,例如:

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.

推荐答案

另外,你可以放弃超载,只是适当命名的属性:

Alternatively, you can of course forego overloading and just name the properties appropriately:

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

当然,你不必让这个只写,但它似乎是适当的。

Of course you don't have to make this WriteOnly but it seems appropriate.

这篇关于同一属性,不同类型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆