扩展类是一种静态的一种类的调用方法,通过实例化进行调用。利用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);
}
}
|