在C#(以及许多其他语言)中,访问相同类型的其他实例的私有字段是完全合法的.例如:
public class Foo
{
private bool aBool;
public void DoBar(Foo anotherFoo)
{
if (anotherFoo.aBool) ...
}
}
Run Code Online (Sandbox Code Playgroud)
由于C#规范(第3.5.1,3.5.2节)规定对私有字段的访问属于类型,而不是实例.我一直在与同事讨论这个问题,我们试图找出它之所以如此工作的原因(而不是限制对同一个实例的访问).
我们可以提出的最佳参数是进行相等性检查,其中类可能希望访问私有字段以确定与另一个实例的相等性.还有其他原因吗?或者一些绝对意味着它必须像这样或某种东西工作的黄金理由是完全不可能的?
class TestClass
{
private string _privateString = "hello";
void ChangeData()
{
TestClass otherTestClass = new TestClass();
otherTestClass._privateString = "world";
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码在C#中编译,并且在PHP中等效,但有人可以解释为什么otherTestClass._privateString可以在这里更改?
我认为类的实例在任何情况下都不应该能够更改私有成员变量,并且尝试访问otherTestClass._privateString会因"保护级别"错误而导致"无法访问".
但事实并非如此,那么为什么在自己的类中实例化一个对象可以让你访问私有成员呢?如果它,这不会破坏封装到一定程度?还是我错过了一些明显的东西?
Edit - Thanks for the answers and comments. To clarify, I'm also interested in knowing if being able to do this is regarded as a positive feature, or if it's a necessary tradeoff for better compile-time checking/code clarity/because most other languages do it that way or whatever. It seems to me …
回答什么是你最长的编程假设,结果是不正确的?问题,其中一个错误的假设是:
私有成员变量对实例是私有的,而不是类.
(链接)
我无法理解他正在谈论的内容,任何人都可以用一个例子来解释这是错误/正确的吗?
我们的商业模式中有一个学生班.令我感到奇怪的是,如果我们操纵另一名学生的一名学生,学生的私人成员是可见的...这让我觉得有点不雅:)
class Program {
static void Main(string[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.ExamineStudentsMembers(s2);
}
}
public class Student {
private String _studentsPrivateMember;
public Student() {
_studentsPrivateMember = DateTime.Now.Ticks.ToString();
}
public void ExamineStudentsMembers(Student anotherStudent) {
//this seems very wrong
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
}
Run Code Online (Sandbox Code Playgroud)
我可以对设计考虑因素/含义有所了解吗?您似乎无法隐藏兄弟姐妹的信息.有没有办法将字段或成员标记为对同一类的其他实例隐藏?