Can you use generic forms in C#?

会有一股神秘感。 提交于 2021-02-15 10:18:33

问题


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.


回答1:


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.




回答2:


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 (i.e without <>) is still found.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/10905/can-you-use-generic-forms-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!