简体   繁体   English

具有不同类型的C#WinForm?

[英]C# WinForm with different Types?

I have a form which encapsulates all the functionality, but works with a concrete Type T1 . 我有一个封装所有功能的表单,但是可以与具体的Type T1一起使用 Now I want to create the same form with the difference, that it will use another Type T2 . 现在,我要创建具有不同之处的相同表单,它将使用另一个Type T2

T1 and T2 don't inherit from anything , so I can't use inheritance. T1和T2不继承任何东西 ,所以我不能使用继承。

How could I do that without copying the whole code again and again? 我如何才能做到一次又一次不复制整个代码?

I was thinking about creating a generic Form, but I don't think that's a correct solution. 我当时正在考虑创建通用表单,但是我认为这不是正确的解决方案。

Any ideas? 有任何想法吗?

Write T2, copy all of the code and make sure to encapsulate all the differences in separate methods. 编写T2,复制所有代码,并确保将所有差异封装在单独的方法中。 Then create a new base class and move the common code from both. 然后创建一个新的基类,并从两者中移出通用代码。 A code-sharing design becomes much more obvious (including whether you should use generics) after you have two classes which need it, rather than trying to plan ahead. 在拥有两个需要共享代码的类之后,而不是事先进行计划,代码共享设计就变得更加明显(包括是否应使用泛型)。

What do you do with T1 and T2 in the form? 您如何处理表格中的T1和T2? If you want to expose/accept values in a strongly typed way, generics sounds like exactly the right approach - although it can be tricky with the WinForms designer, IIRC. 如果要以强类型显示/接受值,则泛型听起来似乎是正确的方法-尽管使用WinForms设计器IIRC可能会比较棘手。

To put it another way: if you weren't using WinForms, would you reach for generics? 换句话说,如果您不使用WinForms,可以使用泛型吗?

I use a generic element to encapsulate my object, this has a text value and a tag value, it allows for things like what you're trying to do, one good use is for adding to a combo box. 我使用一个通用元素来封装我的对象,它具有一个文本值和一个标记值,它允许您尝试执行的操作,一种很好的用途是添加到组合框。 Maybe you could incorporate something like this into your form? 也许您可以将这样的内容合并到您的表单中?

public class GenericElement<T> {
    public GenericElement(string text) {
        this.Text = text;
    }
    public GenericElement(string text, T tag) : this(text) {
        this.Tag = tag;
    }
    public T Tag {
        get; set;
    }
    public string Text {
        get; set;
    }
    public override string ToString() {
        return Text;
    }
}

// Combo-Box example
public class MyForm : Form {
    private void DoLoad(object sender, EventArgs e) {
        comboNum.Items.Add(new GenericElement<int>("One", 1);
        comboNum.Items.Add(new GenericElement<int>("Two", 2);
        comboNum.Items.Add(new GenericElement<int>("Three", 3);
    }
    public int SelectedNumber {
        get {
            GenericElement<int> el =
                comboNum.SelectedItem as GenericElement<int>;
            return el == null ? 0 : el.Tag;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM