Tool:Visual Studio 2013 Ultimate Update 4
OS:Windows 8.1
在C#中,可以定義Extension Method (擴充方法),為型別新增新功能,例如以下為String型別新增Print1與Print2方法,在Main方法中,所有字串都可以叫用Print1與Print2方法,但是要分兩行叫用:
class Program {
static void Main( string[ ] args ) {
string s1 = "mary";
s1.Print1( );
s1.Print2( );
}
}
static class StringExtension {
public static void Print1( this string s ) {
Console.WriteLine( "Print 1 : " + s );
}
public static void Print2( this string s ) {
Console.WriteLine( "Print 2 : " + s );
}
}
static void Main( string[ ] args ) {
string s1 = "mary";
s1.Print1( );
s1.Print2( );
}
}
static class StringExtension {
public static void Print1( this string s ) {
Console.WriteLine( "Print 1 : " + s );
}
public static void Print2( this string s ) {
Console.WriteLine( "Print 2 : " + s );
}
}
執行結果:
我們可以修改擴充方法,使其回傳被擴充的型別,修改程式如下,這樣就可以在一行直接叫用Print1與Print2兩個擴充方法:
class Program {
static void Main( string[ ] args ) {
string s1 = "mary";
s1.Print1( ).Print2( );
}
}
static class StringExtension {
public static string Print1( this string s ) {
Console.WriteLine( "Print 1 : " + s );
return s;
}
public static string Print2( this string s ) {
Console.WriteLine( "Print 2 : " + s );
return s;
}
}
沒有留言:
張貼留言