2011-03-31 66 views
3

可能重複:
What does 「this」 mean in a static method declaration?當使用這個關鍵字作爲函數參數

通過代碼片段我去,發現這個關鍵字作爲函數的參數。 代碼片段就像是

public static void AddCell(this Table table, object cell) 

爲什麼AddCell有this關鍵字,他們可以編寫AddCell(Table table, object cell)

請說明情況時,使用該關鍵字與小的代碼示例作爲一個結果,我可以更好地理解函數的參數。謝謝。

回答

1

此語法用於擴展方法。

這些看起來有點奇怪,當你第一次看到他們寫的,但他們是神話般的東西 - 大部分Linq被寫爲擴展方法。

這裏有一個很好的介紹教程 - http://csharp.net-tutorials.com/csharp-3.0/extension-methods/ - 其中包括例如:

public static class MyExtensionMethods 
{ 
    public static bool IsNumeric(this string s) 
    { 
     float output; 
     return float.TryParse(s, out output); 
    } 
} 

這使您可以撥打:

"fred".IsNumeric() 
1

this是創建extension methods的關鍵字。

這樣,雖然我沒有更改Table的實現,但我可以撥打方法AddCellTable的成員。

MSDN:

擴展方法使您「添加」 方法,現有的類型,而 創建一個新的派生型, 重新編譯,或者修改 原始類型。擴展方法 是一種特殊的靜態方法, 但它們被調用,就好像它們是 上的擴展類型的實例方法。 對於用C#和 Visual Basic編寫的客戶端代碼,在調用 擴展方法和實際在類型中定義 的方法之間並沒有明顯的差異 。

1

這是一個聲明extension method。關鍵在於,以及

MyStaticClass.AddCell(table, cell); 

現在你只需撥打

table.AddCell(cell); 

假設MyStaticClass是在當前的命名空間或命名空間你已經using版。

1

'this'關鍵字用於創建擴展方法。例如,如果您正在使用要添加方法的庫類而不繼承新的派生類型,則可以創建靜態擴展方法。它是一種將常規靜態方法放置在已知類型上的語法糖。

例如:

public static int ToNumber(this string numberString) 
{ 
    int convertedInt = 0; 
    // logic goes here to convert to an int 
    return convertedInt; 
} 

可以這樣調用:

string myNumberString = "5"; 
int num = myNumberString.ToNumber(); 

你沒有創建一個繼承類要做到這一點,但它乾淨讀取。

2

基本上什麼正在在你的例子定義爲一個擴展方法。在靜態方法中,如果使用this關鍵字定義第一個參數,則允許在第一個參數上定義的類型的實例對象上調用該方法。

在這個例子中,你說,你將能夠做這樣的事情:

Table someTableInstance; /// must be instanciated somehow; 
someTableInstance.AddCell(cell); // Call the AddCell method as if it was an instance method. 

希望它能幫助, 問候, 布魯諾

相關問題