来自静态上下文的虚方法

use*_*869 0 c# oop

我有一个BaseProgram充当所有其他程序的基类.
我想为HandleException() 此类添加一个可覆盖的方法以进行错误处理.
从这个BaseProgram派生的所有程序都应该可以选择编写自己的版本HandleException().

所以,我必须声明HandleException()如下virtual方法:

abstract class BaseProgram
{
    public abstract void Run();

    public static void RunWithExceptionHandling(BaseProgram programToRun)
    {
        try
        {
            //do some processing 
            programToRun.Run();
        }
        catch (Exception)
        {
           HandleException();  //Error : Can't access non-static method in static context
        }
    }

    public virtual void HandleException()
    { 
        //Do some basic exception handling here
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不能在静态方法的catch块调用这个新的虚拟方法: RunWithExceptionHandling() 此外,由于应用程序的设计,我不能改变RunWithExceptionHandlingstatic,以非static:-(

任何想法如何解决这个问题所以我可以允许派生类有自己的版本HandleException()

Sri*_*vel 6

好吧,你有实例; 你只需要用它来调用方法.HandleException如果存在,那将调用派生版本.

public static void RunWithExceptionHandling(BaseProgram programToRun)
{
    try
    {
        //do some processing 
        programToRun.Run();
    }
    catch (Exception)
    {
       programToRun.HandleException();//Use the instance :)
    }
}
Run Code Online (Sandbox Code Playgroud)