猿问

教我们如何使用 Delegate 并在 C# 中引发事件

我有 2 个类,Printer 和 MessageOrigin。打印机实例化 MessageOrigin。在 MessageOrigin 类中,我可以获得我需要的消息,但我必须将其返回给 Printer 类,以便将其写入控制台。我想我必须使用 Delegate 和 Event Raiser 来做到这一点。那里有很多教程和解释,但真的很难理解它,更不用说实施它了。可能通过解决我在这里遇到的问题会让你更容易理解如何使用它。请看下面我的示例代码,教我们如何在 C# 中使用委托和引发事件。


Class Printer

{

    MessageOrigin mo = new MessageOrigin();


    printMessage(string message) {

        console.WriteLine(message) // message here should come from the MessageOrigin class

    }

}


class MessageOrigin

{

    public void GetMessage() {

        var msgs = Get_All_Message();

        SendMessageToPrintClass(msgs);

    }

    public void SendMessageToPrintClass(string message) {

        // how do I send the "message" parameter back to the Printer class

    }

}

感谢您的耐心等待。



守着一只汪
浏览 86回答 2
2回答

心有法竹

您可以使用事件。该类MessageOrigin将是发布者,该类Printer将是订阅者。优点是以后您可以添加更多订阅者,而无需更改类MessageOrigin。class Printer{&nbsp; &nbsp; MessageOrigin mo = new MessageOrigin();&nbsp; &nbsp; public Printer()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; mo.NewMessage += PrintMessage; // Subscribe to the event&nbsp; &nbsp; }&nbsp; &nbsp; void PrintMessage(string message)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(message);&nbsp; &nbsp; }}class MessageOrigin{&nbsp; &nbsp; public event Action<string> NewMessage; // Declare the event&nbsp; &nbsp; public void GetMessage()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; string msgs = Get_All_Message();&nbsp; &nbsp; &nbsp; &nbsp; NewMessage?.Invoke(msgs); // Raise the event&nbsp; &nbsp; }}

汪汪一只猫

如果我理解正确,我认为你不需要代表(尽管)你可以使用它。如果您想访问 Printer 类/对象。我的建议是(如果您的体系结构允许的话)将打印机对象的引用传递给 MessageOrigin 类。你可以这样实现:public class Printer{&nbsp; &nbsp; private MessageOrigin mo;&nbsp; &nbsp; public Printer()&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; mo = new MessageOrigin(this);&nbsp; &nbsp; }&nbsp; &nbsp; public void printMessage(string message)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(message); // message here should come from the MessageOrigin class&nbsp; &nbsp; }}public class MessageOrigin{&nbsp; &nbsp; private Printer _parentPrinter;&nbsp; &nbsp; public MessageOrigin(Printer print)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _parentPrinter = print;&nbsp; &nbsp; }&nbsp; &nbsp; public string Get_All_Message()&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //implementation&nbsp; &nbsp; &nbsp; &nbsp; return string.Empty;&nbsp; &nbsp; }&nbsp; &nbsp; public void GetMessage() {&nbsp; &nbsp; &nbsp; &nbsp; var msgs = Get_All_Message();&nbsp; &nbsp; &nbsp; &nbsp; SendMessageToPrintClass(msgs);&nbsp; &nbsp; }&nbsp; &nbsp; public void SendMessageToPrintClass(string message) {&nbsp; &nbsp; &nbsp; &nbsp; // how do I send the "message" parameter back to the Printer class&nbsp; &nbsp; &nbsp; &nbsp;_parentPrinter.Message = message //note that you need to implement your message method/property.&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答