問題描述:this
在某個窗口下的編碼中使用瞭如下擴展方法FindControl,以求根據字符串的值去操做控件(本文中的控件爲Label控件)的屬性。編碼
public static Control FindControl(this Control parentControl, string findCtrlName)orm
{字符串
Control _findedControl = null;string
if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)io
{泛型
foreach (Control ctrl in parentControl.Controls)擴展
{foreach
if (ctrl.Name.Equals(findCtrlName))引用
{
_findedControl = ctrl;
break;
}
}
}
return _findedControl;
}
使用後錯誤列表中顯示錯誤,錯誤描述爲」擴展方法必須在非泛型靜態類中定義「,錯誤的指示下劃線指到了代碼段中的Form2處。
解決方案:
在相同的名稱空間下新建了一個靜態類,類名爲ExtensionClass,而後把擴展方法代碼移至該類中。以下圖:
而後在Form2的代碼塊中經過引用該方法,實現了目的,以下圖: