C# 修改传递给事件处理程序的结构?

C# 修改传递给事件处理程序的结构?,c#,c#-4.0,event-handling,struct,pass-by-reference,C#,C# 4.0,Event Handling,Struct,Pass By Reference,这似乎是一个相当基本的概念,我不明白 在为键盘驱动程序编写.NET包装时,我会为每个按下的键广播一个事件,如下所示(下面的简化代码): 提前谢谢。像这样的事情可能会奏效: if (OnKeyPressed != null) { // Give the subscriber a chance to process/modify the keystroke var args = new KeyPressedEventArgs(stroke);

这似乎是一个相当基本的概念,我不明白

在为键盘驱动程序编写.NET包装时,我会为每个按下的键广播一个事件,如下所示(下面的简化代码):


提前谢谢。

像这样的事情可能会奏效:

if (OnKeyPressed != null)     
{         
  // Give the subscriber a chance to process/modify the keystroke         
  var args = new KeyPressedEventArgs(stroke);
  OnKeyPressed(this, args);     
  stroke = args.Stroke;
} 
给您的订户一份副本,然后在他们完成后将其复制回您的本地值


或者,您可以创建自己的代表击键的类并将其传递给订阅者吗?

在KeyPressedEventArg的构造函数中传递您的结构是通过引用传递的,但也就是说,只要修改stroke变量,它都是通过值传递的。如果您继续通过<代码> REF 传递此结构,您可能需要考虑为其编写包装类。从长远来看,更好的设计决策。

使
stroke
为空只需将实际值放入一个包装器中,该包装器包含一个布尔值,指示值是否存在。包装的值从一开始就是一个值类型。除了@EricJ.的注释之外,可空类型本身也是值类型,尽管值类型从编译器得到了很多特殊处理。工作非常完美,很抱歉这个简单的问题。
public class KeyPressedEventArgs : EventArgs
{
    // I thought making it a nullable type might also make it a reference type..?
    public Stroke? stroke;

    public KeyPressedEventArgs(ref Stroke stroke)
    {
        this.stroke = stroke;
    }
}

// Other application modifying the keystroke

void interceptor_OnKeyPressed(object sender, KeyPressedEventArgs e)
{
    if (e.stroke.Value.Key.Code == 0x3f) // if pressed key is F5
    {
        // Doesn't really modify the struct I want because it's a value-type copy?
        e.stroke.Value.Key.Code = 0x3c; // change the key to F2
    }
}
if (OnKeyPressed != null)     
{         
  // Give the subscriber a chance to process/modify the keystroke         
  var args = new KeyPressedEventArgs(stroke);
  OnKeyPressed(this, args);     
  stroke = args.Stroke;
}