为什么泛型结构不能是非托管的



请查看以下代码:

namespace ConsoleApp
{
public struct MyPoorGenericStructThatCannotBeUnmanaged<T> where T: unmanaged
{
public T Field;
}
public class MyClass<T> where T: unmanaged
{
}
class Program
{
static void Main()
{
// The type 'MyPoorGenericStructThatCannotBeUnmanaged<int>' must be a non-nullable value type, 
// along with all fields at any level of nesting, 
// in order to use it as parameter 'T' in the generic type or method 'MyClass<T>'
var obj = new MyClass<MyPoorGenericStructThatCannotBeUnmanaged<int>>(); 
}
}
}

编译失败,出现错误:

类型"MyPoorGenericStructHatCannotBeUnmanaged"必须是不可为null的值类型,以及任何级别的所有字段嵌套,以便将其用作泛型类型中的参数"T"或方法"MyClass">

然而,MyPoorGenericStructThatCannotBeUnmanaged<int>是一个不可为null的值类型,并且它在嵌套的任何值处的所有字段实际上都是不可为Null的值类型。它由通用类型约束where T: unmanaged确保

为什么?

在解决限制之前,您可以使用基于Unsafe的解决方法。

这就是解决方法的样子:

public unsafe class ArrayOfGenericStructs<TStruct> : IDisposable where TStruct:struct
{
private void* pointer;
public ArrayOfGenericStructs(int size)
{
pointer = (void*) Marshal.AllocHGlobal(Unsafe.SizeOf<TStruct>() * size);
}
public bool IsDisposed { get; private set; }
public void Dispose()
{
if (IsDisposed) return;
IsDisposed = true;
if (pointer != null) Marshal.FreeHGlobal(new IntPtr(pointer));
pointer = null;
}
public ref TStruct this[int index]
{
get
{
return ref Unsafe.AsRef<TStruct>(Unsafe.Add<TStruct>(pointer, index));
}
}
}

相关内容

最新更新