扩展方法学习笔记(二)
在上一篇中,我大概学习了扩展方法的基本语法和结构,下面我来假想一些应用
上一篇链接地址:http://www.cnblogs.com/zqonline/archive/2009/11/09/1598839.html
一、定义基类型的扩展方法对子类会有什么影响?
基类:
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
子类
'窗
Public Class Window
Inherits Door
End Class
扩展方法定义
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
测试
Sub Main()
'门
Dim d As New Door
d.Open()
Console.WriteLine("门:" & d.DoorState.ToString)
d.Close()
Console.WriteLine("门:" & d.DoorState.ToString)
'窗
Dim w As New Window
w.Open()
Console.WriteLine("窗:" & w.DoorState.ToString)
w.Close()
Console.WriteLine("窗:" & w.DoorState.ToString)
Console.ReadKey()
End Sub
'门
Dim d As New Door
d.Open()
Console.WriteLine("门:" & d.DoorState.ToString)
d.Close()
Console.WriteLine("门:" & d.DoorState.ToString)
'窗
Dim w As New Window
w.Open()
Console.WriteLine("窗:" & w.DoorState.ToString)
w.Close()
Console.WriteLine("窗:" & w.DoorState.ToString)
Console.ReadKey()
End Sub
通过上面的例子我们可以看出window也扩展了Close方法,这就是扩展方法的好处啊。在没有扩展方法时,如果我们需要增加Close方法,那就得用重载了,代码需要这样写:
Public Module DoorFun
Sub Close(ByVal d As Door)
d.DoorState = False
End Sub
Sub Close(ByVal w As Window)
w.DoorState = False
End Sub
End Module
Sub Close(ByVal d As Door)
d.DoorState = False
End Sub
Sub Close(ByVal w As Window)
w.DoorState = False
End Sub
End Module
调用时
' d.Close()
DoorFun.Close(d)
' w.Close()
DoorFun.Close(w)
不太优雅。扩展方法确实不错。
提出问题:如果Door的Close与Window的Close处理方式不一样时,如何进行处理?或是Window想自己实现Close时,可以实现吗?
扩展方法与类本身的方法不会产生冲突只是一个补充
Window增加Close方法,这时,扩展方法对于Window来说是无效的,可以理解为类自己的行为高于扩展的行为。如果类自身行业的方法签名与扩展方法不一样时,扩展方法也是可以调用的。