回答什么是你最长的编程假设,结果是不正确的?问题,其中一个错误的假设是:
私有成员变量对实例是私有的,而不是类.
(链接)
我无法理解他正在谈论的内容,任何人都可以用一个例子来解释这是错误/正确的吗?
可能重复:
为什么私有字段对该类型是私有的,而不是实例?
考虑以下课程:
public class Test
{
protected string name;
private DateTime dateTime;
public Test(string name)
{
this.name = name;
this.dateTime = DateTime.Now;
}
public Test(Test otherObject)
{
this.name = otherObject.name;
this.dateTime = otherObject.GetDateTime();
}
private DateTime GetDateTime()
{
return dateTime;
}
public override string ToString()
{
return name + ":" + dateTime.Ticks.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的构造函数中,我正在调用私有或受保护的东西otherObject.为什么这可能?我一直认为私有是真的私有(暗示只有对象可以调用该方法/变量)或受保护(只能通过重载访问).
为什么以及何时需要使用这样的功能?
我缺少一些OO逻辑/原理吗?