這似乎是一個我不明白的基本概念。修改傳遞給事件處理程序的結構體?
在寫一個.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);
}
中風是一種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'爲空可以將你的實際值放入一個包含指示值是否存在的布爾值的包裝器中。包裝值從一開始就是一個值類型。 – 2012-03-12 04:24:55
除了@ EricJ。的評論,可以爲null的類型本身也是值類型,儘管值類型從編譯器中獲得了很多特殊的處理。 – phoog 2012-03-13 04:43:45