扩展方法学习笔记(一)
扩展方法使用前提:
1.只在在模块中定义。
2.必须要引入命名空间System.Runtime.CompilerServices
3.相应的扩展方法上必须使用ExtensionAttribute进行标记
扩展方法的作用:
使用了扩展方法,为了扩展一个类就可以不用创建一个子类了。可以以比较低的成本完善类的实现。
下面是使用扩展方法的例子:
类定义
Public Class Door
Private state As Boolean = False
Property DoorState() As Boolean
Get
Return Me.state
End Get
Set(ByVal value As Boolean)
Me.state = value
End Set
End Property
Sub Open()
Me.state = True
End Sub
End Class
Private state As Boolean = False
Property DoorState() As Boolean
Get
Return Me.state
End Get
Set(ByVal value As Boolean)
Me.state = value
End Set
End Property
Sub Open()
Me.state = True
End Sub
End Class
比如,我还需要定义一个Close方法。在没有扩展方法时,我们提倡使用子类来实现,这样就会造成一个问题,实例化基类型时是没有Close方法的。
下面是实现扩展方法的模块代码
Public Module DoorExpand
<Extension()> _
Public Sub Close(ByVal this As Door)
this.DoorState = False
End Sub
End Module
<Extension()> _
Public Sub Close(ByVal this As Door)
this.DoorState = False
End Sub
End Module
测试代码:
Dim d As New Door
d.Open()
Console.WriteLine(d.DoorState.ToString)
d.Close()
Console.WriteLine(d.DoorState.ToString)
Console.ReadKey()
d.Open()
Console.WriteLine(d.DoorState.ToString)
d.Close()
Console.WriteLine(d.DoorState.ToString)
Console.ReadKey()
完全按照预想结果运行。