我不知道这个问题是有足够的描述,但为什么这又如何行为存在?:C#为什么以及如何在同一个包含类中访问类本身之外的私有变量?
public class Layer
{
public string Name { get; set; }
private IEnumerable<Layer> children;
public IEnumerable<Layer> Children
{
get { return this.children.Where (c => c.Name != null).Select (c => c); }
set { this.children = value; }
}
public Layer ()
{
this.children = new List<Layer> (); // Fine
Layer layer = new Layer ();
layer.children = new List<Layer> (); // Isn't .children private from the outside?
}
}
我可以访问任何地方layer.Children
,这很好,但我怎么能访问layer.children
,因为它是私有的?
Layer layer = new Layer ();
layer.children = new List<Layer> ();
只适用于代码在Layer
类中。是否有特殊的代码来处理访问私有变量,如果它是在包含类中完成的,即使访问是从外部访问的?
我知道使用的原因:
this.children = ...
包含类里面,但创建新实例,并从外部对其进行修改,即使他们仍然含有类中,似乎并不像一个良好的做法。
这是什么原因?