[英]What's the meaning of “this” keyword here?
一個非常短的C#函數。
public static int SizeInBytes(this byte[] a)
{
return sizeof (int) + a.Length*sizeof (byte);
}
“this”關鍵字在此函數中的含義是什么? 在C ++中,這個關鍵字的等價物是什么? 此外,這個功能試圖准確計算什么?
它將該方法標記為擴展方法 。
擴展方法允許您擴展任何類的功能,即使它是密封的。
例:
public static class StringExtensions { public static bool IsEmpty(this string s) { return s == string.Empty; } }
請注意,正確的語法包括靜態類中的靜態方法以及this關鍵字的使用。
關於第二個問題,有一個在 C ++等效.....這是這一點 。 但是,C ++不支持擴展方法,所以你永遠不會像在你提供的代碼片段中那樣在C ++中看到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.