【发布时间】:2012-03-28 12:50:32
【问题描述】:
这似乎是一个我不明白的非常基本的概念。
在为键盘驱动程序编写 .NET 包装器时,我会为按下的每个键广播一个事件,如下所示(下面的简化代码):
// The event handler applications can subscribe to on each key press
public event EventHandler<KeyPressedEventArgs> OnKeyPressed;
// I believe this is the only instance that exists, and we just keep passing this around
Stroke stroke = new Stroke();
private void DriverCallback(ref Stroke stroke...)
{
if (OnKeyPressed != null)
{
// Give the subscriber a chance to process/modify the keystroke
OnKeyPressed(this, new KeyPressedEventArgs(ref stroke) );
}
// Forward the keystroke to the OS
InterceptionDriver.Send(context, device, ref stroke, 1);
}
Stroke 是一个struct,其中包含按键的扫描码和一个状态。
在上面的代码中,由于我通过引用传递值类型结构,因此对结构所做的任何更改在传递给操作系统时都将被“记住”(以便可以拦截和修改按下的键)。所以没关系。
但是如何让我的OnKeyPressed 事件的订阅者修改struct Stroke?
以下不起作用:
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
}
}
提前致谢。
【问题讨论】:
-
使
stroke可以为空只是将您的实际值放入一个包装器中,该包装器包含一个指示值是否存在的布尔值。包装的值从一开始就一直是值类型。 -
对于@EricJ. 的评论,可空类型本身也是值类型,尽管值类型从编译器中得到了很多特殊处理。
标签: c# c#-4.0 event-handling struct pass-by-reference