Visual Basic 9.0 supports the query function integrated with the next generation of languages, and supports relational queries on DLinq data objects or XLinq XML data, these queries are implemented by using a group of methods (or operators) on DLinq or XLinq related objects. VB9 developers think that this query method should also be used to organize existing object data, such as IEnumerable and other sets. Therefore, Visual Basic 9.0 requires a function to add methods to existing types externally.Extension Method.
The extension method is actually a method for Compiler background translation. It was originally a method for accepting T-type parameters and can be written in the syntax of T-type members. This syntax is only used by class library designers and should not be used in disorder. Therefore, Visual Basic 9.0 does not provide special syntax support, the class library designer only needs to place the corresponding Attribute on the module and method that declares the extension method.
<Extension()>Module MyExtensionModule MyExtension<Extension()> _Public Function Count()Function Count(Of T)([Me] As IEnumerable(Of T))As IntegerFor Each Dim item In [Me] Count += 1NextEnd FunctionEnd Module
Note: we name the first parameter of the Extension Method "Me" to remind programmers that after the extension method takes effect, this parameter is just like the instance method "Me". Of course this is not necessary, it is just a recommended practice.
The extension method should work, not without any conditions. If anyone expands the methods in the Framework, it will mess up a pot of porridge. Therefore, it is required to use the Imports statement to import the module where the extension method is located to make the extension method take effect.
Imports MyExtionsion
After importing the extension method, you can use this extension method:
Dim arr = {1, 2, 3, 4, 5} Dim length = arr. Count. The above sentence is automatically translated into 'dim length = MyExtionsion. Count (arr)
The last note is that the extension method is just syntactic sugar and it is best not to use it if there is no need for extension. Too many extensions lead to clear syntax, but poor design. Consider using this feature carefully.