2008 vb.net的扩展方法初试
扩展方法(Extension Methods)是一种静态方法,可以通过实例方法的语法进行调用。从最终效果上看,扩展方法使得扩展一个现有类型和构造一个具有附加方法的类型变成了现实。(注:3.5才可用)
1Imports System.Runtime.CompilerServices
2''' <summary>
3''' 偶的扩展类
4''' </summary>
5''' <remarks></remarks>
6Module myExtension
7 ''' <summary>
8 ''' 返回一定长度的字符串
9 ''' </summary>
10 ''' <param name="str">输入字符串</param>
11 ''' <param name="len">返回长度</param>
12 ''' <returns></returns>
13 ''' <remarks></remarks>
14 <Extension()> _
15 Public Function getString(ByVal str As String, ByVal len As Integer) As String
16 Return Left(str, len)
17 End Function
18End Module
2''' <summary>
3''' 偶的扩展类
4''' </summary>
5''' <remarks></remarks>
6Module myExtension
7 ''' <summary>
8 ''' 返回一定长度的字符串
9 ''' </summary>
10 ''' <param name="str">输入字符串</param>
11 ''' <param name="len">返回长度</param>
12 ''' <returns></returns>
13 ''' <remarks></remarks>
14 <Extension()> _
15 Public Function getString(ByVal str As String, ByVal len As Integer) As String
16 Return Left(str, len)
17 End Function
18End Module
调用:
1Module Module1
2
3 Sub Main()
4 Dim str As String = "没剑圣域"
5 Console.WriteLine(str.getString(12))
6 End Sub
7
8End Module
2
3 Sub Main()
4 Dim str As String = "没剑圣域"
5 Console.WriteLine(str.getString(12))
6 End Sub
7
8End Module
如图示,string类下已多了个扩展方法getString
运行效果: