简体   繁体   中英

Can you use generic forms in C#?

You should be able to create a generic form:

public partial class MyGenericForm<T> :
    Form where T : class
{
    /* form code */
    public List<T> TypedList { get; set; }
}

Is valid C#, and compiles. However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.

I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name.

Yes you can! Here's a blog post I made a while ago with the trick:

Designing Generic Forms

Edit: Looks like you're already doing it this way. This method works fine so I wouldn't consider it too hacky.

I have a hack to workaround this, which works but isn't ideal:

Add a new class to the project that inherits the form with its simple name.

internal class MyGenericForm:
    MyGenericForm<object> { }

This means that although the designer is still wrong the expected simple type (ie without <> ) is still found.

You can do it in three steps.

1) Replace in Form1.cs File

public partial class Form1<TEntity, TContext> : Formbase // where....

2) Replace in Form1.Designer.cs

 partial class Form1<TEntity, TContext>

3) Create new file : Form1.Generic.cs (for opening design)

partial class Form1
{
}    

If paleolithic code doesn't affraid you

    public  static MyForm GetInstance<T>(T arg) where T : MyType
{
    MyForm myForm = new MyForm();

    myForm.InitializeStuffs<T>(arg);
    myForm.StartPosition = myForm.CenterParent;

    return myForm;
}

Use it

var myFormInstance = MyForm.GetInstance<T>(arg);                                                                      myFormInstance.ShowDialog(this);

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