[英]Why aren't WPF controls private by default?
In WPF, writing 在WPF中,写作
<TextBlock x:Name="foo"/>
will make the control public
. 将控制
public
。 To make it private
, one must explicitly specify the FieldModifier
: 要使其成为
private
,必须明确指定FieldModifier
:
<TextBlock x:Name="foo" x:FieldModifier="private"/>
I find this strange. 我觉得这很奇怪。 I don't think it is a good coding style to access a subcontrol directly from outside the class.
我不认为直接从课外访问子控件是一种很好的编码风格。 For example, I would avoid writing
例如,我会避免写作
var muc = new MyUserControl();
muc.foo.Text = "foo";
Instead I would write a public method and use it: 相反,我会写一个公共方法并使用它:
public void SetFooText(string text) { foo.Text = text; }
// in somewhere else
var muc = new MyUserControl();
muc.SetFooText("foo");
or write a public property 或写一个公共财产
public string FooText
{
get { return foo.Text; }
set { foo.Text = value; }
}
// in somewhere else
var muc = new MyUserControl();
muc.FooText = "foo";
So, I don't really see any advantages setting controls to public
by default. 所以,我没有看到默认情况下将控件设置为
public
的任何优点。 Maybe it would be safer if private
is the default, like everything in C#. 如果
private
是默认的,就像C#中的所有东西一样,也许会更安全。
Why is public
the default? 为什么
public
默认?
Well, I made a mistake. 好吧,我搞错了。 The default is
internal
as others have mentioned. 默认是
internal
正如其他人提到的那样。 But the question why it is not private
is still waiting for an answer. 但是为什么它不是
private
的问题仍在等待答案。
Default value of the x:FieldModifier for C# is NotPublic(Internal) C#的默认值:C#的FieldModifier是NotPublic(内部)
TypeAttributes.NotPublic is the default behavior because it is infrequent that code outside the assembly that compiled the XAML needs access to a XAML-created element.
TypeAttributes.NotPublic是默认行为,因为编译XAML的程序集外部的代码很少需要访问XAML创建的元素。 WPF security architecture together with XAML compilation behavior will not declare fields that store element instances as public, unless you specifically set the x:FieldModifier to allow public access.
WPF安全体系结构与XAML编译行为一起不会声明将元素实例存储为公共的字段,除非您专门设置x:FieldModifier以允许公共访问。
As we see if they were private by default assembly which compiled the XAML would not have access to it XAML-created element. 正如我们所看到的那样,默认情况下它们是私有的,编译XAML的程序集将无法访问XAML创建的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.