[StructLayout(LayoutKind.Sequential)] 和 TypeAttributes.SequentialLayout 的区别?

Difference between [StructLayout(LayoutKind.Sequential)] and TypeAttributes.SequentialLayout?

我使用

为P/Invoke动态构建了一个结构
const TypeAttributes typeAttributes = TypeAttributes.Public | 
                                      TypeAttributes.SequentialLayout | 
                                      TypeAttributes.UnicodeClass;
var typeBuilder = moduleBuilder.DefineType("MyType", typeAttributes, typeof(ValueType));

之后,我构造 StructLayoutAttribute 并将其添加到这样的类型中

ConstructorInfo structLayoutAttributeConstructorInfo = typeof(StructLayoutAttribute).GetConstructor(new[] { typeof(LayoutKind) });

FieldInfo charSetFieldInfo = typeof(StructLayoutAttribute).GetField(nameof(StructLayoutAttribute.CharSet));
CustomAttributeBuilder attr = new CustomAttributeBuilder(structLayoutAttributeConstructorInfo,
                                                         new object[] { LayoutKind.Sequential },
                                                         new FieldInfo[] { charSetFieldInfo },
                                                         new object[] { CharSet.Unicode });
typeBuilder.SetCustomAttribute(structLayoutAttributeBuilder);

相当于设置

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]

现在,无论我是否将 StructLayoutAttribute 应用于该结构,代码都可以正常工作

貌似设置属性是多余的,还是我漏了什么?

Type.IsLayoutSequential 属性 的 MSDN 文档说明如下(强调我的):

For dynamic types, you can specify TypeAttributes.SequentialLayout when you create the type. In code, apply the StructLayoutAttribute attribute with the LayoutKind.Sequential enumeration value to the type, to specify that layout is sequential.

所以对你来说相关的部分是 TypeAttributes 标志。分别指定 StructLayoutAttribute 是多余的或无效的。