开发者

c# virtual method

开发者 https://www.devze.com 2023-04-02 06:52 出处:网络
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?

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?

  1. virtual base method code execute
  2. overridden method code execute
  3. 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号