繁体   English   中英

如何获得通过委托处理程序调用的方法的结果?

[英]How do I get the result of a method called via delegate handler?

以下代码只是一个家庭作业,因此委托可能看起来完全没有意义

所以,我有一个刽子手游戏 class ,它有一个从文件中读取游戏数据的方法。 如果未找到该文件 - 应调用用户代码中的方法:

 catch (FileNotFoundException)
 {
   exceptionOnLoad?.Invoke("File doesn't exist");
 }

所以我有一个委托和一个处理方法,它为它分配一个自定义用户方法:

public delegate bool ExceptionErrorHandler(string message);
private ExceptionErrorHandler? exceptionOnLoad;
public void RegisterExceptionErrorHandler(ExceptionErrorHandler method)
{
   exceptionOnLoad = method;
}

所以这里有一个来自用户代码的方法, exceptionOnLoad 应该调用:

static bool HandleOnErrorMessage(string message)
{      
   Console.WriteLine(message);
   return true;
}

它返回 bool,因为我想用它作为停止 Hangman 游戏的指标,但它是通过以下构造调用的,并且没有地方可以将 bool 值写入:

hangmanGame.RegisterExceptionErrorHandler(HandleOnErrorMessage);

有没有办法将 HandleOnErrorMessage 的布尔结果存储在变量中? 或者也许有更好的方法来使用委托并在这种情况下取得理想的结果? 我在想这个:

catch (FileNotFoundException)
{
   bool? load = exceptionOnLoad?.Invoke("File doesn't exist");
}

然后制作一个文件加载方法也是output这个bool,不过这个好像很奇怪(可能是白费了)。 提前致谢。

如果它是为了家庭作业,我会只是.invoke() 它就像一个简单的方法,正如你所描述的。

老实说,这不是一个奇怪的解决方案,这里唯一奇怪的是作业本身。 当然,除了了解代表之外,我认为这样做没有任何意义。

这是控制台应用程序中的一个工作示例:

// We define the delegate
public delegate bool Handler(string message); 

// We assign a handler method with a lambda
public static Handler SomeHandler => HandlerMethod; 

public static bool HandlerMethod(string message)
{
    // Do what you need with the message and return a value
    return true;
}

static void Main(string[] args)
{
    // We call it and store the value in a variable!
    var variable = SomeHandler.Invoke("Some message"); 
}
// you declared the delegate
public delegate bool ExceptionErrorHandler(string message);

// if you want to return the output of the delegate method, it needs to return 
// same type as such delegate
public bool RegisterExceptionErrorHandler(ExceptionErrorHandler method)
{  
    const string message = "Call from RegisterExceptionErrorHandler";
    if (method != null)  // can be null, yes
        return method(message);
    else
        return false;
}


// USAGE

private void DoSomething(SomeEnum val)
{

    bool retval;

    if (val == SomeEnum.Val1) // Based on enum value
        retval = RegisterExceptionErrorHandler(Method1); // you invoke one method or another
    else if (val == SomeEnum.Val2)
        retval = RegisterExceptionErrorHandler(Method2);
    else 
        retval = RegisterExceptionErrorHandler(Method3);

    if (retval)
        RunSomeCode();

}

方法Method1Method2Method3必须使用delegate的签名声明 - bool X(string)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM