簡體   English   中英

無法將類型'System.Windows.Forms.Control'轉換為'T'

[英]Cannot convert type 'System.Windows.Forms.Control' to 'T'

我試圖創建一個通用的FindControl方法,我得到以下錯誤:

無法將類型'System.Windows.Forms.Control'轉換為'T'

碼:

public T Control<T>(String id)
{
  foreach (Control ctrl in MainForm.Controls.Find(id, true))
  {
    return (T)ctrl; // Form Controls have unique names, so no more iterations needed
  }

  throw new Exception("Control not found!");
}

嘗試這個

public T Control<T>(String id) where T : Control
{
  foreach (Control ctrl in MainForm.Controls.Find(id, true))
  {
    return (T)ctrl; // Form Controls have unique names, so no more iterations needed
  }

  throw new Exception("Control not found!");
}

你總是可以彎曲規則並進行雙重演員。 例如:

public T Control<T>(String id)
{
  foreach (Control ctrl in MainForm.Controls.Find(id, true))
  {
    return (T)(object)ctrl; 
  }

  throw new Exception("Control not found!");
}

由於T不受約束,您可以為type參數傳遞任何內容。 您應該在方法簽名中添加“where”約束:

public T Control<T>(string id) where T : Control
{
    ...
}

你怎么稱呼這個方法,你有一個例子嗎?

另外,我會為你的方法添加一個約束:

public T Control<T>(string id) where T : System.Windows.Forms.Control
{
    //
}

雖然其他人已經正確地指出了問題所在,但我只想說明這非常適合擴展方法。 不要贊成這個,這實際上是一個評論,我只是將它作為答案發布,這樣我就可以更好地編寫代碼並更好地格式化我的代碼;)

public static class Extensions
{
   public static T FindControl<T>(this Control parent, string id) where T : Control
   {
      return item.FindControl(id) as T;
   }
}

所以你可以像這樣調用它:

Label myLabel = MainForm.Controls.FindControl<Label>("myLabelID");

將方法簽名更改為:

public T Control<T>(String id) where T : Control

聲明所有T實際上都是Control類型。 這將約束T並且編譯器知道您可以將其作為T返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM