gpt4 book ai didi

c# - 似乎无法通过引用传递 EventArgs

转载 作者:行者123 更新时间:2023-11-30 16:02:22 25 4
gpt4 key购买 nike

我有一个引发事件的类。我希望订阅者能够修改在 EventArgs 中传递的值。

在引发事件的类中:

    class Factory
{
public event EventHandler<MessageReceivedEventArgs> MessageReceived;

private IServerLib _myObject;

public void Connect()
{
_myObject = new ServerLib();
_myObject.AddMessageReceivedHandler((short terminal, ref string message, ref short functionNo) =>
{
MessageReceivedEventArgs args = new MessageReceivedEventArgs { Terminal = terminal, Message = message, FunctionNo = functionNo };
MessageReceivedEvent(ref args);
});
}

private void MessageReceivedEvent(ref MessageReceivedEventArgs args)
{
EventHandler<MessageReceivedEventArgs> handler = MessageReceived;
if (handler != null)
{
handler(this, args);
}
}

public class MessageReceivedEventArgs : EventArgs
{
public short Terminal { get; set; }
public string Message { get; set; }
public short FunctionNo { get; set; }
}
}


interface IServerLib
{
void AddMessageReceivedHandler(MessageReceivedEventHandler action);
}
public delegate void MessageReceivedEventHandler(short terminal, ref string message, ref short functionNo);

订户(恰好是 VB)如下所示:

Dim WithEvents _va As MyAssembly.MyClass

Private Sub _va_MessageReceived(sender As Object, e As Factory.MessageReceivedEventArgs) Handles _va.MessageReceived
Debug.WriteLine($"Message: {e.Message} Terminal: {e.Terminal} Function: {e.FunctionNo}")
If e.Message = "1" Then
e.Message = ""
e.FunctionNo = 0
Debug.WriteLine("Cancelled")
End If
End Sub

这引发了事件,但设置 e.Message 和 e.Function 似乎没有设置值。我做错了什么吗?

最佳答案

问题出在这一行的使用上:

var args = new MessageReceivedEventArgs
{ Terminal = terminal, Message = message, FunctionNo = functionNo };

它将所有变量复制到事件参数类。在那里更改它不会自动在另一端(您添加 ref 的地方)更改它。这不是一个很好的解决方案,但为了向您证明这是问题所在,请在 handler(this, args) 之后添加:

message = args.Message;
functionNo = args.FunctionNo;

这将导致 ref 覆盖值。

关于c# - 似乎无法通过引用传递 EventArgs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37727472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com