You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何验证结构体已应用StructLayoutAttribute.Pack=1?

验证结构体的StructLayout特性(Pack=1检查)

我正在构建一个限定为特定结构体的泛型类型,需要验证这些结构体是否已应用[StructLayout(LayoutKind.Sequential, Pack = 1)]特性。

基类构造函数中已实现部分验证逻辑:

public abstract class IotDeviceData<T> where T : struct
{
  protected T _data;

  protected IotDeviceData()
  {
    IotDeviceData<T>.IsAnAllowedStruct();
    _data = new T();
  }
}

目前可以检查结构体是否应用了LayoutKind.Sequential:

private static void IsAnAllowedStruct()
{
  var t = typeof(T);
  if(!t.IsLayoutSequential)
  {
    throw (new ArgumentException($"Struct type {t} must have a sequential layout."));
  }
}

但不知道如何检查Pack是否为1?


解决方案

要验证Pack是否为1,需直接获取结构体上的StructLayoutAttribute特性实例,读取其Pack属性值。修改后的IsAnAllowedStruct方法如下:

private static void IsAnAllowedStruct()
{
    var t = typeof(T);
    // 验证顺序布局
    if (!t.IsLayoutSequential)
    {
        throw new ArgumentException($"Struct type {t} must have a sequential layout.");
    }

    // 获取并验证StructLayout的Pack值
    var structLayoutAttr = Attribute.GetCustomAttribute(t, typeof(StructLayoutAttribute)) as StructLayoutAttribute;
    if (structLayoutAttr == null || structLayoutAttr.Pack != 1)
    {
        throw new ArgumentException($"Struct type {t} must have StructLayout with Pack = 1.");
    }
}

说明:

  • 使用Attribute.GetCustomAttribute获取目标结构体的StructLayoutAttribute实例
  • 先判断特性是否存在(避免结构体未标注该特性的情况),再校验Pack属性是否等于1
  • 不满足条件时抛出明确的异常信息

内容的提问来源于stack exchange,提问作者Martin Gonzalez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:15:14