扩展方法小记

什么是扩展方法?

我的理解是:在变量原有基础上做 扩展 在原有基础上增加新业务,就是扩展方法

例子:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace TuozhanTest
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string speack = "奥特曼";
14             string outSpeack = speack.ExtendString();
15 
16             int a = 21;
17             int s = a.ExtendInt();
18 
19             Console.WriteLine(outSpeack);
20             Console.WriteLine(s);
21 
22             Console.ReadKey();
23         }
24     }
25 
26     //扩展类
27     static class ExtendClass 
28     {
29         public static int ExtendInt(this int sum) 
30         {
31             return sum + 100;//定义的变量调用这个扩展方法可以自己+100
32         }
33 
34         public static string ExtendString(this string conn) 
35         {
36             return $"{conn},欢迎光临";//定义的字符串变量调用这个扩展方法可以加个  欢迎光临
37         }
38     }
39     
40 }

扩展类要点:1.方法必须为静态的;2.参数必须带this;  3.扩展方法的所在类必须是静态的

posted on 2022-06-13 10:55  泰坦尼克号上的活龙虾  阅读(42)  评论(0)    收藏  举报

导航