I have this generic function
T AddControl<T>() where T : WebControl, new() {
T ctrl = new T();
if (ctr开发者_如何学Pythonl is Label) {((Label)ctrl).Text = "FirstName :";}
return ctrl; }
I get the error: "Cannot convert Type 'T' to 'System.Web.UI.Webcontrols.Lable'" What would be the proper way of casting. Thanks in advance. BB
You can use as
instead:
T AddControl<T>() where T : WebControl, new() {
T ctrl = new T();
Label label = ctrl as Label;
if (label != null)
{
label.Text = "FirstName :";
}
return ctrl;
}
精彩评论