無法修改第三方/BCL 型別源碼時,傳統做法建立靜態 Helper 類,呼叫不直觀 (Helper.Do(obj))。
public static class PropertyExtension
{
public static object GetValueByName(this object self, string propertyName)
{
if (self == null) return null;
var prop = self.GetType().GetProperty(propertyName);
return prop?.GetValue(self, null);
}
}
static。this 修飾,型別為欲擴充的型別 (此處 object)。
string s = "abc";
object len = s.GetValueByName("Length"); // 如同實例方法
// 等價於
object len = PropertyExtension.GetValueByName(s, "Length");
L_0008: ldstr "Length"
L_000d: call object PropertyExtension::GetValueByName(object, string)
編譯器將實例呼叫語法重寫為靜態方法呼叫,無運行時開銷。

方法圖示帶藍色向下箭頭,標識為擴充方法。
object),否則所有型別皆出現該方法。