如何让 Visual Studio 使用带参数的构造函数生成代码?
例如:
添加ContextMenuStrip时,MyForm.designer.cs中生成InitializeComponent()这行代码
this.MyMenuStrip= new System.Windows.Forms.ContextMenuStrip(this.components);
使用 dotPeek 来反射(reflect) ContextMenuStrip 并没有给我任何有用的方法。
我想制作一个自定义控件,当将其拖放到任何 System.Windows.Forms.Control 时,设计器将调用参数构造函数而不是无参数构造函数。
最佳答案
来自the MSDN page about the design-time features of Windows Forms ,看来具有以 IContainer 作为参数的构造函数的组件是一种特殊情况:
A component can let the designer know that it would like to be notified when its container goes away by implementing a public constructor that takes a single argument of type IContainer, as shown in this snippet:
class ClockComponent : Component {
public ClockComponent(IContainer container) {
// Add object to container's list so that
// we get notified when the container goes away container.Add(this);
}
// ...
}
Notice that the constructor uses the container to add itself as a container component. In the presence of this constructor, the designer will generate code that uses this constructor, passing it a container for the component to add itself to.
另请参阅Customizing Code Generation in the .NET Framework Visual Designers在 MSDN 上。
关于c# - 如何让 Visual Studio 中的设计器使用参数化构造函数生成组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21027443/