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

EG。我想检索10的值。

[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public byte[] _value1;
}
有帮助吗?

解决方案

是的,有反思:

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

(未经测试,显然缺少相当多的错误检查,但应该有效。)

其他提示

var x = new StructureToMarshalFrom();
var fields = x.GetType().GetFields();

var att = (MarshalAsAttribute[])fields[0].GetCustomAttributes(typeof(MarshalAsAttribute), false);
if (att.Length > 0) {
    Console.WriteLine(att[0].SizeConst);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top