Create method to handle multiple types of controls
I a开发者_开发问答m trying to create a method that accepts multiple types of controls - in this case Labels and Panels. The conversion does not work because IConvertible doesn't convert these Types. Any help would be so appreciated. Thanks in advance
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);
}
}
Wouldn't you want a where constraint on control like so:
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);
}
The where
constraint forces control
to be of type WebControl so no conversion is necessary. Because of the where
constraint, you know that control
is a class and can be compared to null and that it has a Controls collection.
I also change the code to throw an exception if control
is null. If you really just wanted to ignore situations where a null argument is passed, then simply change that throw new ArgumentNullException("control");
to return null;
. Given the compile constraint, I would think that passing a null to your routine would be unexpected and should throw an exception however I do not know how your code will be used.
精彩评论