我正在构建一个泛型类型,仅限于某些类型的结构,并且需要验证是否有[StructLayout(LayoutKind)]。顺序的,包= 1)]属性应用。
在基本构造函数中验证结构类型:
public abstract class IotDeviceData<T> where T : struct
{
protected T _data;
protected IotDeviceData()
{
IotDeviceData<T>.IsAnAllowedStruct();
_data = new T();
}
}
我可以检查LayoutKind。
private static void IsAnAllowedStruct()
{
var t = typeof(T);
if(!t.IsLayoutSequential)
{
throw (new ArgumentException($"Struct type {t} must have a sequential layout."));
}
}
但是,如何检查Pack是否为1呢?
您可以直接获得StructLayoutAttribute
并检查其Pack
:
if ((type.StructLayoutAttribute?.Pack ?? 0) != 1) {
throw (new ArgumentException($"Struct type {type} must have a pack of 1"));
}