你能在 C# 中使用泛型表单吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you use generic forms in C#?
提问by Keith
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.
是有效的 C#,并编译。但是,如果您有任何图像表明它找不到资源,则设计器将无法工作,并且表单将引发运行时异常。
I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name.
我认为这是因为 windows 窗体设计器假定资源将存储在简单类型的名称下。
采纳答案by Matt Hamilton
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.
编辑:看起来你已经这样做了。这种方法效果很好,所以我不会认为它太黑了。
回答by Keith
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 (i.e without <>
) is still found.
这意味着尽管设计者仍然是错误的,但<>
仍然可以找到预期的简单类型(即没有)。
回答by Ali Osman Yavuz
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
{
}
回答by Nando
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);