Make class extension simpler-extension methods and extension methods

Source: Internet
Author: User

Make class extension simpler-extension methods and extension methods

1. What is an extension method?

An extension method is a method that can be used to extend the method members of a defined type.

Before an extension method is created, if you want to customize a new method with special logic for an existing type, you must redefine a type to inherit the existing type. In this way, add a method. If the base class has an abstract method, you need to implement it again.

In this way, in order to expand a method, more overhead is required due to inheritance. Using inheritance to extend an existing type is a little useless, and the value type or sealed class (class that cannot be inherited) cannot be inherited, and thus cannot be extended.

Therefore, C #3.0 proposed an extension method.

 

2. Use of extension methods

2.1 define extension methods

1 public static class ListExtern
  2     {
  3 public static int JSum (this IEnumerable <int> source)
  4 {
  5 if (source == null)
  6 {
  7 throw new ArgumentException ("The input array is empty");
  8             }
  9 int jsum = 0;
10 bool flag = false;
11
12 foreach (var i in source)
13 {
14 if (! Flag)
15 {
16 jsum + = i;
17 flag = true;
18}
19 else
20 {
21 flag = false;
twenty two                 }
twenty three             }
24 return jsum;
25}
26}

In the above Code, the JSum method is an extension method, which is used to calculate the sum of the elements of an array with an odd number of labels. Not all methods can be used as extension methods. The following are the definition rules that comply with the extension method:

(1) The extension method must be defined in a non-nested, non-generic static class;

(2) It must have at least one parameter;

(3) The first parameter must be prefixed with the "this" keyword (the first parameter type is also known as the extension type, that is, the method is used to expand this type );

(4) The first parameter cannot use any other modifier (for example, it cannot use a modifier such as ref or out );

(5) The type of the first parameter cannot be a pointer.

These rules are rigid rules. No matter which method violates, the compiler may report an error or think that the method is not an extension method.


2.2 call the Extension Method

After defining an extension method, call it.


1 static void Main (string [] args)
2         {
3 List <int> source = new List <int> () {1,2,3,4,5,6,3};
4 int jsum = source.JSum ();
5 Console.WriteLine ("The odd sum of the array is:" + jsum);
6 Console.ReadKey ();
7}

A successful call illustrates the uniqueness of an extended method call. Here, you can call an extended method directly by using the List <int> type.

 

3. How the compiler discovers extension methods

For the C #3.0 compiler, when it sees a type of variable calling a method, it will first go to the instance method of the object for search, if no instance method with the same name as the called method and the same parameter is found, the compiler will go back and find the appropriate extension method.

The compiler checks all imported naming controls and the extension methods in the current naming control, and matches the variable type to the extension type. An extension method for implicit conversion exists here. For example, in the previous code, an implicit conversion exists from List <T> to the extended type IEnumerable <int>.

From the compiler's process of discovering extension methods, the priority sequence of method calls should be: Type instance method-extension method under the current namespace-Extension Method for importing the namecontrol. The following code demonstrates how the compiler discovers a method:


1 namespace extension method 2
 2 {
 3 using extension method 3;
 4 class Program
 5 {
 6 static void Main (string [] args)
 7 {
 8 Person p = new Person () {Name = "哈哈"};
 9 p.Print ();
10 p.Print ("Hello");
11}
12}
13
14 public class Person
15 {
16 public string Name {get; set;}
17}
18
19 public static class Extensionclass
20 {
21 public static void Print (this Person per)
twenty two         {
23 Console.WriteLine ($ "calls the extension method output under the current namespace, the name is: {per.Name}");
twenty four         }
25}
26}
27
28 namespace extension method 3
29 {
30 using extension method 2;
31
32 public static class CustomExtensionClass
33 {
34 public static void Print (this Person per)
35 {
36 Console.WriteLine ($ "calls the extension method under the CustomNamaspace namespace: name: {per.Name}");
37}
38
39 public static void Print (this Person per, string s)
40 {
41 Console.WriteLine ($ "calls the extension method under the CustomNamaspace namespace. The name is: {per.Name}, additional string {s}");
42}
43}
44
45}

In the above Code, there are two different naming controls, both of which define the extension method Print with a parameter. Based on the analysis of the priority of the method called by the compiler, the compiler first checks whether the Print instance method without parameters is defined in the Person type. If yes, stop searching. Otherwise, continue searching for the current namespace, that is, whether the extension method Print with a parameter is defined in CurrentNamespace.

Note: (1) if the Print instance method without parameters is defined in the extended type, when the "." operator is typed after p, the VS smart prompt will not provide the extended method.

(2) If two classes in the same namespace contain methods of the same extension type, the compiler will not know which method to call, and a compilation error will occur.

 

4. The extension method can also be used for empty references.

4.1 speak with examples


1 namespace extension method 3
  2 {
  3 class Program
  4 {
  5 static void Main (string [] args)
  6 {
  7 Console.WriteLine ("Demonstration of calling extension method on empty reference:")
  8 string s = null;
  9 Console.WriteLine ($ "String S is an empty string: {s.IsNull ()}");
10 Console.ReadKey ();
11}
12}
13
14 public static class NullExtern
15 {
16 public static bool IsNull (this object obj)
17 {
18 return obj == null;
19}
20}
twenty one }

The above Code does not report an exception and can run properly. However, in the above Code, the Code extends the object type, and all types inherited from the object will have this extension method, which produces "pollution" to other child types ".

Better implementation methods should be:

1 public static bool isNull(this string str)
2 {
3      return str==null;  
4 }

So when we define an extension method for a type, we should try to extend the specific type instead of its base class. The reason why NullReferenceException does not occur when calling an extension method on a null reference is that for the compiler, the null reference "S" is used as a parameter to pass in a static method, that is, s. the call of IsNull is equivalent to the following code: Console. writeLine ($ "string s is an empty string {NullExten. isNull (s)} "); this is not really calling the method on the null reference, so there is no exception.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.