Skip to content
February 27, 2013 / windperson

C# prviate access modifier一直以來的錯誤認知

現在有這樣的一段C#程式碼:

public class Account {
    private int amount;
	
    public void Transfer(Account acc, int delta) {
        acc.amount += delta;
        this.amount -= delta;	
    }
}

第5行acc.amount += delta;怎麼看怎麼怪,那個amount不是private field嗎?怎麼能夠這樣子在不是自己的物件上存取到???

查看MSDN上對於private keyword的解釋:

The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared.

所以一直以來認為private是控制『物件』存取權限的觀念,根本是錯的啊……@@

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: