[英]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.是有效的 C#,并编译。 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.我认为这是因为 windows 窗体设计器假定资源将存储在简单类型的名称下。
Yes you can!是的你可以! Here's a blog post I made a while ago with the trick:
这是我不久前用这个技巧写的一篇博客文章:
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:我有一个 hack 来解决这个问题,它有效但并不理想:
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 1) 在 Form1.cs 文件中替换
public partial class Form1<TEntity, TContext> : Formbase // where....
2) Replace in Form1.Designer.cs 2)在Form1.Designer.cs中替换
partial class Form1<TEntity, TContext>
3) Create new file : Form1.Generic.cs (for opening design) 3) 创建新文件:Form1.Generic.cs(用于打开设计)
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.