The extended method is derived from List <T>Where, Order, GroupByAnd other methods, smart sensing prompts that these methods are extension methods, so MSDNSummary:Custom Extension Method (convert string to Int, Code copy)
Namespace MyCommon
{
Public static class EString
{
Public static int ToInt (this string t)
{
Int id;
Int. TryParse (t, out id); // The id returned when the conversion fails.
Return id;
}
}
}
Required, Extension Method: 1, Must be static class and static method (and must be public)
2, The parameter must use thisPrefix
At first glance, the extension method obviously violates the encapsulation principle and sets the method to public.For external calls, this is a very illegal encapsulation principle, but there is no way here, if it is changed to privateExternal instances cannot be accessed, but Microsoft told us that although the syntax of the instance method is used to call the extension method, the IL generated by the compilerIn the intermediate language, the code is converted into a call to a static method. In theory, the encapsulation principle is not really illegal, but this interpretation is somewhat far-fetched.
However, we found that the static class name is EString.It seems useless and can be changed at will. Indeed, all we need here is the namespace and method name, while the MethodThe first parameter determines the type of extension that the extension method is used.For example, the preceding example is this string t.The type of the first parameter is string., Is the stringExtension Method