属性集重载数组与非数组
我正在尝试创建一个属性,允许根据各种输入设置姓氏。调用此函数的代码正在解析名称字段。在某些情况下,它有一个姓氏,而在其他情况下,它有一个需要连接的姓氏数组。我想将串联代码保存在一个位置以便于维护。
这是我的代码,当然不起作用:
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
Public WriteOnly Property LastName() As String()
Set(ByVal value As String())
For Each word As String In value
_LastName &= word & " "
Next
_LastName = _LastName.Trim
End Set
End Property
我已经尝试了多种变体,甚至将多个 Set 放在同一个属性中,但似乎没有任何效果。必须有某种方法来获取数组和单个实例值。编译器清楚地知道传入的对象是否是数组。
我尝试仅使用 String() 类型的属性,但无法返回字符串。我能想到的唯一解决方案是使用不同名称的属性,这使得使用类变得更加困难,或者一大堆 Subs 和 Functions 相互重载。
建议?
克里斯
I'm trying to create a property that will allow the setting of a last name based on a variety of inputs. The code that calls this is parsing a name field. In some instances it will have a single last name, in others, a array of last names that need to be concatenated. I want to keep my concatenation code in a single place to make maintenance easier.
Here is my code, which of course doesn't work:
Public Property LastName() As String
Get
Return _LastName
End Get
Set(ByVal value As String)
_LastName = value
End Set
End Property
Public WriteOnly Property LastName() As String()
Set(ByVal value As String())
For Each word As String In value
_LastName &= word & " "
Next
_LastName = _LastName.Trim
End Set
End Property
I've tried numerous variations on this, even putting multiple Set in the same Property, but nothing seems to work. There must be some way to take in an array and a single instance value. The compiler clearly knows if the incoming object is an array or not.
I tried working with just a property of type String(), but then I can't return a String. The only solution that I can think of is differently named properties, which makes using the class more difficult, or a whole bunch of Subs and Functions overloading each other.
Suggestions?
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能重载属性,因此属性可以是
string
或string()
,但不能同时使用两者。考虑为
string()
属性使用不同的名称:You cannot overload properties, so the property can by either a
string
or astring()
, not both.Consider having a different name for the
string()
property:如果您的输出与输入的类型不同,则不能为其使用属性。使用函数并没有什么问题,好的做法是你有函数名称 (
LastName
),并在其前面添加一个动词 (Get
),所以你最终会得到一个类似GetLastName
的函数。(如果有什么明显的错误,请原谅我生锈的 VB)
If your output is going to be of a different type than your input, then you cannot use a property for it. There is nothing wrong with using a function for it, good practice would say that you have the function name (
LastName
), and prepend a verb on to it (Get
), so you end up with a function anme likeGetLastName
.(excuse my very rusty VB if there is something blatantly wrong)
像这样的事情怎么样:
有人认为这有问题吗?
What about something like this:
Does anyone see a problem with this?