1

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

例如。我想检索 10 的值。

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

2 回答 2

4

是的,有反思:

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

(未经测试,显然缺乏很多错误检查,但应该可以。)

于 2008-10-14T13:59:59.083 回答
1
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);
}
于 2008-10-14T14:07:25.870 回答