1

我有以下用于创建 web 控件的方法(现在只是文字和面板)

private T CreateControl<T>(string s1, string s2, string m1)
    where T: WebControl , new()
{
    T ctrl = default(T);

   if (ctrl is Literal )
    {
       Literal l = new Literal();
       l.ID = s1 + "ltl" + s2;
       l.Text = s1 +  " " + s2;
       ctrl = (Literal)l;
    }
    else if (ctrl is Panel)
    {
        Panel p  = new Panel();
        p.ID = s1+ "pnl" + s2;
        p.CssClass = s1 + "graphs";
        p.Attributes.Add("responsefield", s2);
        p.Attributes.Add("metricid", m1);
        ctrl = (Panel)l;

    }
    else if (ctrl is CheckBox)

       return ctrl;
}

我将其调用为:

Literal lg = CreateControl<Literal>("emails", name.Name, name.MetricId.ToString() );

但转换失败:

ctrl = (Literal)l;
ctrl = (Panel)p;

错误:

Cannot implicitly convert type 'System.Web.UI.WebControls.Panel' to 'T' 

有人可以建议如何处理这种转换吗?

提前致谢...

4

1 回答 1

2

我可以建议你这样的事情。

private T CreateControl<T>(string s1, string s2, string m1)
where T : System.Web.UI.Control,new()
{

    if (typeof(T) == typeof(Literal))
    {
        Literal l = new Literal();
        l.ID = s1 + "ltl" + s2;
        l.Text = s1 + " " + s2;
        return l as T;
    }
    else if (typeof(T) == typeof(Panel))
    {
        Panel p = new Panel();
        p.ID = s1 + "pnl" + s2;
        p.CssClass = s1 + "graphs";
        p.Attributes.Add("responsefield", s2);
        p.Attributes.Add("metricid", m1);
        return p as T;

    }
    else if (typeof(T) == typeof(CheckBox))
    {
        return new CheckBox() as T;
    }
    else
    {
        return new T();
    }
}

编辑:修改了你不需要像@jbl建议的那样事后强制转换的方法。

Literal l = CreateControl<Literal>("something", "something", "something");
于 2013-09-11T07:19:01.490 回答