0
我有一個C#.NET 2.0 CF項目,我使用了許多本地方法。其中有幾種方法圍繞着某種類型的對象HANDLE
。我想抽象出使用泛型這樣把手管理的生命週期:用泛型管理本地句柄
public abstract class IHandleTraits
{
public abstract IntPtr Create();
public abstract void Release(IntPtr handle);
}
public sealed class SafeHandle<T> : IDisposable where T : IHandleTraits
{
private bool disposed;
private IntPtr handle_ = NativeMethods.INVALID_HANDLE_VALUE;
public SafeHandle()
{
// error CS0119: 'T' is a 'type parameter', which is not valid in the given context
handle_ = T.Create();
if (NativeMethods.INVALID_HANDLE_VALUE == handle_)
{
// throw win32 exceptions
}
}
~SafeHandle()
{
this.Dispose(false);
}
public IntPtr Handle
{
get { return handle_; }
}
public void Dispose(bool disposing)
{
if (this.disposed)
{
// error CS0119: 'T' is a 'type parameter', which is not valid in the given context
T.Release(handle_);
handle_ = NativeMethods.INVALID_HANDLE_VALUE;
}
this.disposed = true;
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
}
現在,我可以定義一個特徵結構,每個手柄式是這樣的:
internal sealed class MyHandleTraits : IHandleTraits
{
// error CS0112: A static member cannot be marked as override, virtual, or abstract
public static override IntPtr Create()
{
return NativeMethods.CreateHandle();
}
// error CS0112: A static member cannot be marked as override, virtual, or abstract
public static override void Release(IntPtr handle)
{
NativeMethods.ReleaseHandle(handle);
}
}
而且在使用它應用程序是這樣的:
using (SafeHandle<MyHandleTraits> MyHandle = new SafeHandle<MyHandleTraits>)
{
// execute native methods with this handle
}
顯然,這有幾個問題:
- 如何爲
static
函數定義abstract
接口? - 當我嘗試使用泛型,我得到一個錯誤,說它是一個「類型參數」,它是「在給定的上下文中無效」。
我能做些什麼來解決或解決這些問題?
感謝, PaulH
我按照您的建議重新安排了對象層次結構。再次感謝。 – PaulH 2010-09-27 20:45:38