开发者

How to Protect Base Field's Public/Private

If i have a ClassA

    public class ClassA
    {
        public string name;
    }

Where Attribute Name is Public ,and it can be modified from Anywhere . Than i have a ClassB

    public class ClassB : ClassA
    {开发者_如何学编程
        private string name;//But it's not Woking ,name is still public
    }

...which Inherit's ClassA ,but i need at ClassB to make name as Private Field. So if i create an Object of Type ClassB than ClassB.name cannot be modified .


just don't publish the field but accessors:

public class ClassA
{
    private string _name;
    public string Name { get { return _name; } protected set { _name = value; } }
}

public class ClassB : ClassA
{
  /* nothing left to do - you can set Name in here but not from outside */
}


This is not possible. You can not change visibility of base class's field.


Assuming you cannot change A, do not use inheritance, but aggregation and delegation:

public class A {
  public string name;
  public int f() { return 42; }
}

public class B {
  private A a;
  public int f() { return a.f(); }
  public string getName() { return a.name; }
}


Carsten Konig's method is a good way, and here is an alternative.

public class ClassA {
    public virtual string Name {
        get;
        private set;
    }
}

public class ClassB : ClassA {
    public override string Name {
        get {
            return base.Name;
        }
    }
}


Hm. There is a pair of tricks for this. But none of them is what you really want. One is:

    public class ClassA 
    {
        protected string name;
        public string Name { get { return name; } public set { name = value; } }
    }

public class ClassB : ClassA
    {
         public new string Name { get { return base.name; } }
    }


If you don't have control over ClassA, you can do this:

void Main()
{   
    var b = new ClassB();
    var a = (ClassA)b;
    a.name = "hello";
    b.PrintName();
}

class ClassA {
    public string name;
}

class ClassB : ClassA  {
    private new string name;
    public void PrintName() {
        Console.WriteLine(base.name);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜