Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

c# - Why can private member variable be changed by class instance?

class TestClass
{
    private string _privateString = "hello";
    void ChangeData()
    {
        TestClass otherTestClass = new TestClass();
        otherTestClass._privateString = "world";
    }
}

This code compiles in C# and the equivalent works in PHP, but can someone explain the reason why otherTestClass._privateString can be changed here ?

I would have thought an instance of a class should not be able to change a private member variable under any circumstances, and that trying to access otherTestClass._privateString would give an 'inaccessible due to protection level' error.

This is not the case though, so why does instantiating an object inside its own class let you access the private members ? And should it, doesn't this break encapsulation to an extent ? Or am I missing something obvious ?

  • (I'm not asking if the above class design is good practice, just wondering about the theory behind it.)

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 ideally the compiler would prevent or warn you about this, but then I'm far from a language designer. Any examples of how it being this way lets you do something useful (without violating encapsulation) that would otherwise be difficult or impossible would be great.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Private members are accessible to any code within the program text of that class (including within nested types). It has nothing to do with which instance of the class you're dealing with.

I don't believe this violates encapsulation - the API is still separated from the implementation, but the implementation "knows" about itself regardless of which instance it's looking at.

I believe that in some other languages this isn't how accessibility works, but it definitely is for C# and Java. (Java has slightly different rules about what can access private members, but the translated code for what you've written would still work.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...