Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MarshalAsAttribute Sizeconst.NET_C#_.net_Marshalling - Fatal编程技术网

C# MarshalAsAttribute Sizeconst.NET

C# MarshalAsAttribute Sizeconst.NET,c#,.net,marshalling,C#,.net,Marshalling,使用C,有人知道如何在运行时获取MarshalAsAttribute的Sizeconst值吗 我想取10的值 [StructLayout[LayoutKind.Sequential, Pack=1] Class StructureToMarshalFrom { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public byte[] _value1; } 是的,带着反思: FieldInfo field = type

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

我想取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;
未经测试,显然缺少大量的错误检查,但应该可以工作。

是的,有反射:

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);
}
未经测试,显然缺乏大量的错误检查,但应该可以工作

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);
}