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

≡放荡痞女 提交于 2020-01-01 07:40:29

问题


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 just like we do with overriden methods using the base keyword.

Sorry I should have added an example. Here is an example. Hope I get it right:

public class A 
{
    public abstract void AProperty 
    {
        set 
        {
            // doing something here
        }
    }
}

public class B : A 
{   
    public override void AProperty 
    {
        set 
        {
            // how to invoke the base class setter here

            // then add some more stuff here
        }
    }   
}

回答1:


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
    }
}


来源:https://stackoverflow.com/questions/5108319/c-sharp-can-a-base-class-property-be-invoked-from-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!