I have got the following class structure, and have plenty of classes like C derived from B, in some of the classes I dont want by B.OnShow() but I want A.OnShow() to be executed from C Any tricks?
abstract class A
{
protected开发者_高级运维 virtual void OnShow()
{
//some code
base.OnShow();
}
}
class B : A
{
protected override void OnShow()
{
//some other code
base.OnShow();
}
}
class C : B
{
protected override void OnShow()
{
//some other code
base.OnShow();
}
}
Don't have C extend from B, instead make a new class "X" that extends from A and has the parts that are currently in B that you want for both B and C and then have C and B extend from "X". Then B will just have the bits in it that you want for B specifically (a bit abstract, but I think that makes sense).
Generally speaking, if you are trying to skip a parent method then you are doing something wrong.
Eric Lippert has already answered a very similar question and basically stated that it's not permitted in C#.
It sounds like a design problem here. If C really is a B, it should probably do everything B needs to do in the OnShow. If not, you should probably be utilizing something other than direct inheritance, or something other than a single virtual function call.
If you really really wanted to, you could have:
abstract class A
{
protected virtual void OnShow()
{
UniqueOnShowStuff();
base.OnShow();
}
protected virtual void UniqueOnShowStuff()
{
//
}
}
class B : A
{
protected override void OnShow()
{
// Things all B's need to Show
base.OnShow();
}
protected override void UniqueOnShowStuff()
{
// Things most B's might want to show but don't have to
}
}
class C : B
{
protected override void OnShow()
{
// Things all C's need to show
base.OnShow();
}
protected override void UniqueOnShowStuff()
{
// override without a base call so you don't show B's things
}
}
This is a horrible pattern though, and I wouldn't recommend it if you could come up with a better way to redesign the objects/functionality.
精彩评论