简体   繁体   中英

C# WinForm with different Types?

I have a form which encapsulates all the functionality, but works with a concrete Type T1 . Now I want to create the same form with the difference, that it will use another Type T2 .

T1 and T2 don't inherit from anything , so I can't use inheritance.

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. 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? 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.

To put it another way: if you weren't using WinForms, would you reach for generics?

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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