MarshalAsAttribute Sizeconst .NET

Meg*_*yte 2 .net c# marshalling

使用 C#,有谁知道如何在运行时获取 MarshalAsAttribute 的 Sizeconst 值?

例如。我想检索 10 的值。

[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public byte[] _value1;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

是的,反思一下:

FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
int sizeConst = marshal.SizeConst;
Run Code Online (Sandbox Code Playgroud)

(未经测试,并且显然缺乏相当多的错误检查,但应该可以工作。)