문제

I have the following class hierarchy

 public class Third : Second
{
}

public class Second : First
{
}

public class First
{
     private int MyVariable;
}

if i want to access MyVariable from Second and Third, I could make MyVariable protected but what if i want to access from Second but NOT Third. Is that possible?

도움이 되었습니까?

해결책 2

You're not thinking about this in an object-oriented manner.

You state that every Third is a Second. But you want every Second to have access to the variable, but you don't want any Third to have access.

But if Third does not have access, then it is not a Second!

다른 팁

If I want to access MyVariable from Second and Third I could make MyVariable protected. What if I want to access from Second but NOT Third. Is that possible?

Yes! Here's one technique:

class First
{
    private int myVariable;
    public class Second : First
    {
        public Second() { myVariable = 123; } // Legal!
    }
}

class Third : First.Second
{
    public Third() { myVariable = 456; } // Illegal!
}

Here's another:

// Alpha.DLL
public class First 
{ 
    internal int myVariable;
}
public class Second : First
{
    public Second() { myVariable = 123; } // Legal!
}

// Bravo.DLL
class Third : Second
{
    public Third() { myVariable = 456; } // Illegal!
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top