C# Windows 窗体继承
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/826425/
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
Windows Form inheritance
提问by Ronnie Overby
I want to create a bunch of forms that all have the same properties and initialize the properties in the forms constructor by assigning the constructor's parameters.
我想创建一堆具有相同属性的表单,并通过分配构造函数的参数来初始化表单构造函数中的属性。
I tried creating a class that inherits from form and then having all of my forms inherit from that class, but I think since I couldn't call InitializeComponent(), that I was having some problems.
我尝试创建一个继承自表单的类,然后让我的所有表单都继承自该类,但我认为由于我无法调用 InitializeComponent(),所以我遇到了一些问题。
What is some C# code on how to do this?
关于如何执行此操作的一些 C# 代码是什么?
采纳答案by Adam Robinson
The parent's InitializeComponent
should be called by having your constructor call base()
like this:
InitializeComponent
应该通过base()
像这样调用构造函数来调用父对象:
public YourFormName() : base()
{
// ...
}
(Your parent Form should have a call to InitializeComponent
in its constructor. You didn't take that out, did you?)
(您的父 Form 应该InitializeComponent
在其构造函数中调用 to 。您没有将其取出,是吗?)
However, the road you're going down isn't one that will play nicely with the designer, as you aren't going to be able to get it to instantiate your form at design time with those parameters (you'll have to provide a parameterless constructor for it to work). You'll also run into issues where it assigns parent properties for a second time, or assigns them to be different from what you might have wanted if you use your parametered constructor in code.
但是,您要走的路并不适合设计师,因为您将无法在设计时使用这些参数实例化您的表单(您必须提供一个使其工作的无参数构造函数)。如果您在代码中使用参数化构造函数,您还会遇到第二次分配父属性的问题,或者将它们分配为与您可能想要的不同。
Stick with just having the properties on the form rather than using a constructor with parameters. For Forms, you'll have yourself a headache.
坚持只在表单上拥有属性,而不是使用带参数的构造函数。对于表单,您会很头疼。
回答by JoshBerke
An alternate pattern from inheritance here would be to use a factory to create the forms. This way your factory can set all the properties
这里继承的另一种模式是使用工厂来创建表单。这样您的工厂就可以设置所有属性
回答by JupiterP5
Create an interface and pass that into the constructor of the form.
创建一个接口并将其传递给表单的构造函数。
interface IFormInterface
{
//Define Properties here
}
public MyForm(IFormInterface AClass)
{
//Set Properties here using AClass
}
Though I'm usually doing more than just setting properties when I want to do something like this, so I end up creating an abstract class for default behaviors.
虽然当我想做这样的事情时,我通常做的不仅仅是设置属性,所以我最终为默认行为创建了一个抽象类。