c# virtual method
I have base class and Execute virtual method. I override execute method in derived class. Is it possible to execute virtual method code in such flow?
- virtual base method code execute
- overridden method code execute
- virtual base method code execute
Not sure if I hav开发者_JAVA技巧e explained everything well but I hope to get explanation for my question :)
public abstract class ConverterBase
{
public virtual void Execute()
{
try
{
//1. Base class code
// 2. Execute overridden method code.
}
finally
{
//3. Base class code
}
}
}
public class Converter : ConverterBase
{
public override void Execute()
{
//2. code
}
}
No, you want the template method pattern here:
public abstract class ConverterBase
{
public void Execute()
{
try
{
// Stuff
ExecuteImpl();
}
finally
{
// Stuff
}
}
protected abstract void ExecuteImpl();
}
public class Converter : ConverterBase
{
protected override void ExecuteImpl()
{
// Stuff to execute within the parent's try block
}
}
It should be possible by calling base.Execute()
from within your method.
More info: http://msdn.microsoft.com/en-us/library/hfw7t1ce(v=vs.71).aspx
精彩评论