简体   繁体   English

C#可以从派生类调用基类属性吗

[英]C# Can a base class property be invoked from derived class

I have a base class with a property which has a setter method.我有一个带有 setter 方法的属性的基类。 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.有没有办法从派生类调用基类中的 setter 并为其添加更多功能,就像我们使用 base 关键字覆盖方法一样。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM