调用一个覆盖方法的祖父母实施 [英] Calling the grand-parent implementation of an overridden method
问题描述
可能重复:结果
的如何调用base.base.method()?
块引用>
我有一些麻烦,在C#中继承。我已经勾勒三类:
A
,B
和C
。C
从继承乙
和B
从A
。现在B
调用类base.Method1
和工作正常,但我不能叫A .method1
从C
类。如果我称之为base.Method1
从C
显然这种方法将是方法1
B
的。有什么建议?
P.S。在
A
类也有一些田标记为私有,所以你可以访问它们只能A级
{
私有实例;
公共虚拟无效方法1()
{
实例=这一点;
做一些事情;
}
}
B类:A
{
公共覆盖无效方法1()
{
base.Method1( );
做一些事情;
}
}
类C:B
{
公共覆盖无效方法1()
{
//有需要的方法1然后做什么
}
}
解决方案这是C#的一个特点。如果您想公开这个方法来C类,考虑重构一个像这样:
A级
{
私有的实例;
公共虚拟无效方法1()
{
AMethod1();
}
保护无效AMethod1()
{
实例=这一点;
做一些事情;
}
}
这将使你从C调用此方法
C类:b
{
公共覆盖无效方法1()
{
AMethod1();
//做一些事情;
}
}
Possible Duplicate:
How to call base.base.method()?I have some trouble with Inheritance in C#. I've sketched three classes:
A
,B
andC
.C
inherits fromB
andB
fromA
. Now theB
class callsbase.Method1
and works fine but I can't callA.method1
from theC
class. If I callbase.Method1
fromC
obviously that method will bemethod1
ofB
. Any advice?P.S. in
A
class there are some fields marked private so you can access them onlyclass A { private instance; public virtual void Method1 () { instance = this; do something; } } class B : A { public override void Method1() { base.Method1(); do something; } } class C : B { public override void Method1 () { //need A Method1 then do something } }
解决方案This is a feature of C#. If you wish to expose this method to class C, consider refactoring A like so:
class A { private instance; public virtual void Method1 () { AMethod1(); } protected void AMethod1() { instance = this; do something; } }
This will enable you to call this method from within C:
class C : B { public override void Method1 () { AMethod1(); // do something; } }
这篇关于调用一个覆盖方法的祖父母实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!