VB.Net Property? or Method? - 属性还是方法
在VB.net中,我们有属性这一概念,通常的表达格式是:
1 Private _myProperty As String
2 Property myProperty() As String
3 Get
4 Return _myProperty
5 End Get
6 Set(ByVal value As String)
7 _myProperty = value
8 End Set
9 End Property
10
但是在特殊的情况下,我们可能需要一个属性去设置多个值,这时候我们就会考虑到使用方法,传递多个参数。在VB.Net中就可以省略这个步骤,因为VB.Net属性既是方法,我们可以混淆,如下定义:
1 Private _LastName As String
2 Private _FirstName As String
3 Private _FullName As String
4 Property Name(Optional ByVal FirstName As String = "", Optional ByVal LastName As String = "") As String
5 Get
6 Return _FullName + " (FirstName: " + _FirstName + " LastName: " + _LastName + ")"
7 End Get
8 Set(ByVal value As String)
9 _FirstName = FirstName
10 _LastName = LastName
11 _FullName = value
12 End Set
13 End Property
怎么去使用?简单,既当方法调用,又当属性赋值:
1 Dim obj As myCustomClass = New myCustomClass
2 obj.Name("Tom", "Smith") = "Jim John"
3 MessageBox.Show(obj.Name)
VB.Net在识别属性时其实内部他将属性的调用转换成了方法,上面这段代码实质上是对
obj.Name(byVal value As String, Optional ByVal FirstName As String = "", Optional ByVal LastName As String = "")
这样我们就可以混淆实现既是方法又是属性的功能。
WPF QQ交流群: 113404016 欢迎加入