Why can I call a protected or private method / variable CSharp?

Possible duplicate:
Why are private types private to the type and not the instance?

Consider the following class:

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();
    }
}

In my constructor, I call closed or protected material otherObject. Why is this possible? . I always thought that the private was really private (assuming that the object can call this method / variable) or protected (only accessible when overloaded).

Why and when will I have to use this feature?

Is there some kind of OO logic / principle that I am missing?

+5
source share
6 answers

MSDN ( #)

- . - . , .

+5

:

, , Clone. , .

class MyClass : ICloneable
{
    public object Clone()
    {
        var clone = (MyClass)MemberwiseClone();
        clone.Value = this.Value; // without the way private works, this would not be possible
        return clone;
    }

    public int Value{ get; private set;}
}
+3

#. ( , Java .)

, , , .

, - , ..... , "" .

+2

, , , , , .

,

+2

, . testObject , .

Clone(), .

+1
source

Private means that only code in the same class can access it. Here. You have another instance, but it is the same class.

+1
source

All Articles