擴展類是一種靜態的一種類的調用方法,通過實例化進行調用。利用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);
}
}
|
