在寫的P/Invoke包裝爲一個本地的dll的通用功能,我發現自己有很多的代碼看起來像這樣:約束在C#中的委託類型
// Declare delegate types matching some callbacks in the dll
delegate void d1(T1, T1);
delegate void d2(T1,T2,T3);
// Some functions
void f1(T1 a, T2 b)
{
..
}
void f2(T1 a, T2 b, T3 c)
{
}
後來的後來,
// Marshal some instantiated delegates into IntPtrs to pass to native dll
IntPtr a = Marshal.GetFunctionPointerForDelegate(new d1(f1));
IntPtr b = Marshal.GetFunctionPointerForDelegate(new d2(f2));
所以我最終得到了很多類似上面的代碼。我想一些重構使用通用的功能可能是好的,是這樣的:
static void foo<T>(ref IntPtr ptr, T f) where T: System.Delegate, new()
{
ptr = Marshal.GetFunctionPointerForDelegate(new T(f));
}
這將讓我接着寫:
foo<d1>(a,f1);
foo<d2>(b,f2);
等。它不會編譯!我試圖在函數聲明中添加一些類型約束,但無法使其工作。在這種情況下,對我來說並不重要,因爲重新分解幾乎不是很重要,但我只是想知道我會如何做這樣的事情?
很好的解釋,謝謝你的解決方法。 –