C#中的扩展类的理解
2024-09-04 10:19:59
扩展类是一种静态的一种类的调用方法,通过实例化进行调用。利用this进行指正该类,有参数的时候直接在后面追加参数。
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
//必须定义为公共的静态类 public static class Studentinfo{ //定义一个添加学生姓名的扩展方法 public static string AddStuname( this string stuname){ return studentname; } //添加多个参数的扩展方法 public static string AddStudentinfo( this string stuname, string stunum){ return string .Format( "学生信息:\n" + "学生姓名:{0}\n" + "学生学号:{1}" ,stuname,stunum); } } //这种方法跟一般的调用方法一致 //实例化类然后直接使用函数就行 class Students { public static void Main( string [] args){ studentinfo stu= new studentinfo(); string stuinfo=stu.Addstuname(); string stuinfos=stu.AddStudentinfo( "sldkfj" , "001" ); Console.WriteLine(stuinfo); Console.WriteLine(stuinfos); } } //为stu类扩展(一般用于不知道类中的源代码,只知道功能时候) pulic class Stu{ public void foo(){ .... } public void fo( string stuname, string stuno){ .... } } //stu类的扩展类 public static class ExtenStu{ //传参进行类的实例化 public static string ExtenStuAdd( this Stu student){ return student.foo(); } //传参进行类的实例化,有参数在后面追加 public static string ExtenStuAddinfo( this Stu students, string stusname, string stusnum) { return students.fo(stusname,stusnum); } } |
最新文章
- Sharing A Powerful Tool For Application Auto Monitor
- mysql数据库视图连接出现2003····错误
- eclipse简单使用
- 关于sharedPreferences的使用
- python 中转义字符的注释
- javascript设计模式-工厂模式
- android Button 切换背景,实现动态按钮和按钮颜色渐变
- android137 360 双击三击事件
- iOS开发之类扩展
- C# 在PDF中绘制动态图章
- 解决oracle11G密码过期问题
- HDFS API编程
- [MapReduce_add_2] MapReduce 实现年度最高气温统计
- lsof 查看端口占用的进程ID
- cf777c 模拟
- centos7 关闭 防火墙
- [Web 前端 ] ES6 == ES 2015
- ABAP-BarCode-3-调用第三方控件BarTender实现打印
- sqlserver 索引优化 CPU占用过高 执行分析 服务器检查
- Postman-关于设置