2010-03-30 30 views
0

我想創建一種方法,接受多種類型的控件 - 在這種情況下,標籤和麪板。轉換不起作用,因爲IConvertible不轉換這些類型。任何幫助將如此讚賞。 在此先感謝創建方法來處理多種類型的控件

public void LocationsLink<C>(C control) 
    { 
     if (control != null) 
     { 
      WebControl ctl = (WebControl)Convert.ChangeType(control, typeof(WebControl)); 
      Literal txt = new Literal(); 
      HyperLink lnk = new HyperLink(); 
      txt.Text = "If you prefer a map to the nearest facility please "; 
      lnk.Text = "click here"; 
      lnk.NavigateUrl = "/content/Locations.aspx"; 
      ctl.Controls.Add(txt); 
      ctl.Controls.Add(lnk); 
     } 
    } 

回答

3

難道你不希望在控制其中的約束,像這樣:

public void LocationsLink<C>(C control) where C : WebControl 
{ 
    if (control == null) 
     throw new ArgumentNullException("control"); 

    Literal txt = new Literal(); 
    HyperLink lnk = new HyperLink(); 
    txt.Text = "If you prefer a map to the nearest facility please "; 
    lnk.Text = "click here"; 
    lnk.NavigateUrl = "/content/Locations.aspx"; 
    control.Controls.Add(txt); 
    control.Controls.Add(lnk); 
} 

where約束力control是WebControl的類型,所以就沒有必要轉換。由於where約束,您知道control是一個類,可以與null進行比較,並且它具有Controls集合。

如果control爲空,我還會更改代碼以引發異常。如果你真的只想忽略傳遞了null參數的情況,那麼只需將throw new ArgumentNullException("control");更改爲return null;即可。考慮到編譯約束,我認爲將null傳遞給你的例程會是意想不到的,應該拋出一個異常,但是我不知道你的代碼將如何被使用。

+0

謝謝你的回答。您能否進一步採取措施,並說明我在該方法中還會做些什麼以促進轉換?同時,我將研究約束條件。 – Praesagus 2010-03-30 23:56:27

+0

我擴展了我的帖子給你。 – Thomas 2010-03-31 00:37:23

+0

謝謝你花時間解釋它。你剛剛給了我另一個偉大的工具。 – Praesagus 2010-03-31 14:59:55