我正在尝试构建一个动态类型并设置它的大小,就像[StructLayout(LayoutKind.Sequential, Size=100)]可以。我有以下代码:
Type structLayoutAttr = typeof(StructLayoutAttribute);
ConstructorInfo structLayoutAttrCtor = structLayoutAttr.GetConstructor(new[]{typeof(LayoutKind)});
object[] structLayoutAttrCtorArgs = new object[]{LayoutKind.Explicit};
FieldInfo[] structLayoutAttrSizeField = new FieldInfo[]{structLayoutAttr.GetField("Size")};
CustomAttributeBuilder cb = new CustomAttributeBuilder(structLayoutAttrCtor, structLayoutAttrCtorArgs, structLayoutAttrSizeField, new object[]{size});
tb.SetCustomAttribute(cb);
type = tb.CreateType();然而,这段代码在最后一步失败了-- CreateType抛出了关于糟糕格式的TypeLoadException。是否有适当的方法应用该属性?
发布于 2014-11-12 15:41:15
StructLayout属性是一个特殊的属性,它由编译器处理并编译成一个特殊的元数据,因此您不能将它应用于自定义属性构建。检查 overload,有一个类型的大小。
https://stackoverflow.com/questions/26890826
复制相似问题