How can I hide a base class public property in the derived class

后端 未结 16 1574
自闭症患者
自闭症患者 2021-01-01 08:39

I want to hide the base public property(a data member) in my derived class:

class Program
{
    static void Main(string[] args)
    {
        b obj = new b()         


        
16条回答
  •  青春惊慌失措
    2021-01-01 09:16

    namespace PropertyTest    
    {    
        class a
        {    
            int nVal;
    
            public virtual int PropVal
            {
                get
                {
                    return nVal;
                }
                set
                {
                    nVal = value;
                }
            }
        }
    
        class b : a
        {
            public new int PropVal
            {
                get
                {
                    return base.PropVal;
                }
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                a objA = new a();
                objA.PropVal = 1;
    
                Console.WriteLine(objA.PropVal);
    
                b objB = new b();
                objB.PropVal = 10; // ERROR! Can't set PropVal using B class obj. 
                Console.Read();
            }
        }
    }
    

提交回复
热议问题