C#能否在基类属性从派生类中调用 [英] C# Can a base class property be invoked from derived class
本文介绍了C#能否在基类属性从派生类中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有其中有一个setter方法属性的基类。有没有办法来调用派生类的基类的setter和添加更多的功能,它就像我们使用base关键字重写的方法。
对不起,我应该补充一个例子。下面是一个例子。希望我得到它的权利:
大众A级
{
公共抽象无效AProperty
{
组
{
//这里做什么
}
}
}
公共b类:一
{
公共覆盖无效AProperty
{
组
{
//如何调用基类的setter这里
//再加入一些更多的东西在这里
}
}
}
解决方案
修改:修订后的例子应该向世人证明调用的顺序。编译作为控制台应用程序。
类baseTest
{
私人字符串_t =的String.Empty;
公共虚拟串T {
{返回_t;}
组
{
Console.WriteLine(我在基地);
_t =价值;
}
}
}
类派生:baseTest
{
公众覆盖串T {
{返回基地。吨; }
组
{
Console.WriteLine(我在衍生);
base.t =价值; //这个分配调用基二传手
}
}
}
类节目
{
公共静态无效主要(字串[] args)
{
变种TST2 =新的派生();
tst2.t =D;
//输出:
//我在派生
我//我在基地
}
}
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
}
}
}
解决方案
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
}
}
这篇关于C#能否在基类属性从派生类中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文