[英]Does a window's default constructor have to be public?
I'm working on a dialog window for my WPF application. 我正在为我的WPF应用程序创建一个对话框窗口。 I know that WPF requires that all controls have a default constructor and I can create all the constructors that take all the parameters that I want. 我知道WPF要求所有控件都有一个默认构造函数,我可以创建所有带有我想要的参数的构造函数。 But does the default constructor have to be public? 但默认构造函数是否必须公开? Can I make it internal, or private, or even protected? 我可以将其设为内部,私人,甚至保护?
Controls dont need a default constructor in WPF, unless you want to instantiate the control from XAML. 除非您想要从XAML实例化控件,否则控件在WPF中不需要默认构造函数。
It's perfectly legal to have a control like this: 拥有这样的控件是完全合法的:
public partial class MyUserControl : UserControl
{
public MyUserControl(string someParameter) : this()
{
InitializeComponent();
}
}
As shown, the default constructor was removed, you need to make sure that InitializeComponent();
如图所示,删除了默认构造函数,需要确保InitializeComponent();
is called, though. 虽然被称为。
If you instantiate the control from XAML, then the default constructor must be visible by the embedding control 如果从XAML实例化控件,则嵌入控件必须可以看到默认构造函数
Therefore it can be internal
if the embedding control is in the same assembly, or it has to be public
otherwise. 因此,如果嵌入控件在同一个程序集中,它可以是internal
的,否则它必须是public
。
making your constructor internal ensures the type will only ever be instantiated by types within the current assembly, even if it is later decided that the type itself should be public instead of internal. 使你的构造函数内部确保类型只会被当前程序集中的类型实例化,即使后来确定类型本身应该是public而不是internal。 In other words you could decide to change the type's visibility without lifting restrictions on its instantiation. 换句话说,您可以决定更改类型的可见性,而不会限制其实例化。
Making the constructor public has the opposite effect (obviously), and might be sensible if you want for it to be possible to instantiate the type anywhere it is visible. 使构造函数公开具有相反的效果(显然),如果您希望它可以在任何可见的地方实例化该类型,那么这可能是明智的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.