这个简单的程序:
namespace ConsoleApp1;
using System.Data;
using System.Reflection;
using System.Runtime.InteropServices;
internal class Program {
[StructLayout(LayoutKind.Sequential, Pack=4)]
public sealed class Data {
}
static void Main(string[] args) {
StructLayoutAttribute layout = typeof(Data).GetCustomAttribute<StructLayoutAttribute>() ??
throw new NoNullAllowedException("layout");
}
}
投掷。为什么我无法反思这个属性?我需要能够针对双重用途的情况执行此操作,其中 C# 类需要在本机 pinvoke 中序列化,但还需要一个单独的代码生成器能够提取结构包值。
StructLayout
是一个伪属性。
通过反射获取其值的方法是通过 StructLayoutAttribute
上的
Type
属性:
StructLayoutAttribute layout = typeof(Data).StructLayoutAttribute;