C# Can a base class property be invoked from derived class

前端 未结 1 1932
暗喜
暗喜 2021-02-18 23:59

I have a base class with a property which has a setter method. Is there a way to invoke the setter in the base class from a derived class and add some more functionality to it j

1条回答
  •  攒了一身酷
    2021-02-19 00:44

    EDIT: the revised example should demostrate the order of invocations. Compile as a console application.

    class baseTest 
    {
        private string _t = string.Empty;
        public virtual string t {
            get{return _t;}
            set
            {
                Console.WriteLine("I'm in base");
                _t=value;
            }
        }
    }
    
    class derived : baseTest
    {
        public override string t {
            get { return base.t; }
            set 
            {
                Console.WriteLine("I'm in derived");
                base.t = value;  // this assignment is invoking the base setter
            }
        }
    }
    
    class Program
    {
    
        public static void Main(string[] args)
        {
            var tst2 = new derived();
            tst2.t ="d"; 
            // OUTPUT:
            // I'm in derived
            // I'm in base
        }
    }
    

    0 讨论(0)
提交回复
热议问题