我有一段可用的代码,但是我无法解释为什么它能够正常工作。
以这个类为例。
public class TestClass
{
private int _testValue;
public void TestMethod()
{
var t = new TestClass() {_testValue = 42}; // Why is that working?
}
}
为什么这是允许的? 我本以为行为会像这样:
static void Main(string[] args)
{
new TestClass() { _testValue = 23 }; // Does not compile and I am happy with that.
// The code provided will print ‘Hello World’ to the console.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
Console.WriteLine("Hello World!");
Console.ReadKey();
// Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app!
}
编辑:感谢您的评论,但我知道“private”关键字的含义,问题是,当我在同一对象内使用参数构造函数时,为什么我可以访问私有属性。
请放置一个调试器,您会发现TestClass this._testValue
与t._testValue
不同。
在我的想法中,正常行为是在Main函数中所拥有的行为。
Main
属于哪个类?如果它与TestClass
不同,那么您肯定无法访问TestClass
的私有成员。但是在TestMethod
中,您肯定可以访问。这是您的问题吗?为什么TestClass
中的方法可以访问TestClass
的私有成员? - MakePeaceGreatAgainprivate
类成员。TestMethod
是TestClass
的一个成员,因此您可以从该方法访问所有private
成员。 - dymanoidTestMethod
中创建了一个新的TestClass
实例,它与当前实例(this
)无关。您是否期望this
指向与t
相同的实例? - MakePeaceGreatAgainthis._testValue
会等于t._testValue
呢?它们是不同的实例,因此它们的值当然不相同(除非您将它们设置为相同的值)。 - JLeprivate
表示私有于类,而不是实例。 - Lasse V. Karlsen