C#基础知识---扩展方法

一、简介

扩展方法为现有的类型(.Net类型或者自定义类型)扩展应该附加到该类型中的方法。

二、基本原则

  • 定义一个非嵌套非泛型静态类
  • 扩展方法是静态的
  • 扩展方法至少要有一个参数,该参数类型是要扩展的类型
  • 第一个参数必须加上this关键字作为前缀
  • 第一个参数不能用其他任何修饰符(如不能使用ref out等修饰符)
  • 第一个参数的类型不能是指针类型

三、例子

  例1:为.Net类型添加扩展方法

 1 using System;
 2 
 3 namespace ExtensionMethod
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             string myStr = "YuanXi";
10             string tmpStr1 = myStr.GetNotNullString();
11             Console.WriteLine(tmpStr1);
12 
13             myStr = null;
14             tmpStr1 = myStr.GetNotNullString();
15             Console.WriteLine(tmpStr1);
16         }
17     }
18     public static class StringExtension
19     {
20         public static string GetNotNullString(this string str)
21         {
22             return str ?? string.Empty;
23         }
24     }
25 }
View Code

  例2:为自定义类型添加扩展方法

  

 1 using System;
 2 
 3 namespace ExtensionMethod
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             int a = 4;
10             int b = 1;
11             Calculator cal = new Calculator();
12             int r = cal.Add(a, b);
13             int r2 = cal.Sub(a, b);
14             Console.WriteLine($"Add result is: {r}");
15             Console.WriteLine($"Sub result is: {r2}");
16         }
17     }
18     public class Calculator
19     {
20         public int Add(int a, int b)
21         {
22             return a + b;
23         }
24     }
25     public static class CalculatorExtension
26     {
27         public static int Sub(this Calculator cal, int a, int b)
28         {
29             return a - b;
30         }
31     }
32     public static class StringExtension
33     {
34         public static string GetNotNullString(this string str)
35         {
36             return str ?? string.Empty;
37         }
38     }
39 }
View Code

  

猜你喜欢

转载自www.cnblogs.com/3xiaolonglong/p/9662452.html