扩展方法小记

什么是扩展方法?

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

例子:

复制代码
 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   泰坦尼克号上的活龙虾  阅读(30)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示