代码之家  ›  专栏  ›  技术社区  ›  Thunder

带新参数问题的泛型函数

  •  0
  • Thunder  · 技术社区  · 15 年前

    你好, 我有一个通用函数,如下所示。它可以通过调用

    showForm(ch);

    它适用于第二个函数(new without parameter),但是如果我想像第三个函数(new with parameter)那样在构造函数中显示form But with parameter,那么我就不能这样做。有人知道怎么做吗?

           void showForm<T>(T frm)  where T :Form, new()
            {
                if (frm == null)
                {
                    frm = new T();
                }
                frm.MdiParent = this;
                frm.Show();
            }
    
    
            //Works for this
            public frmChild2()
            {
                InitializeComponent();
                ChildToolStrip = toolStrip1;
               // toolStrip1.Visible = false;
            }
    
            //Does not Work for this
            public frmChild2(string title)
            {
                InitializeComponent();
                ChildToolStrip = toolStrip1;
                Text = title;
                // toolStrip1.Visible = false;
            }
    
    2 回复  |  直到 15 年前
        1
  •  5
  •   Jay    15 年前

    使用 Where T : new() T 有一个 public 没有arg构造函数。

    从您所展示的内容来看,不需要在构造函数中设置标题(如何在 showForm 方法甚至知道要设置什么?)。

    T型 Form 你可以设置 frm.Text = 在实例化 形式 .