我有一个引发事件的类。我希望订阅者能够修改在 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 };

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

这将导致 ref s 覆盖这些值。

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

10-13 08:02