在托管C#中声明结构数组的问题? [英] Problem in declaring the array of structures in managed C#?
本文介绍了在托管C#中声明结构数组的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道以前有人问同样的问题。当我试图在网上搜索时,我找不到它。请帮我解决这个问题?
使用系统;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Runtime.InteropServices;
使用 System.Text;
使用 System.Threading.Tasks;
命名空间 ConsoleApplication1
{
class 计划
{
[StructLayout(LayoutKind.Sequential)]
public class 详情
{
public uint ID;
public uint state;
public uint country;
public uint place;
}
[StructLayout(LayoutKind.Sequential)]
public class UserDetails
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst = 8 )]
public Details [] userDetails;
}
静态 void Main( string [] args)
{
UserDetails u = new UserDetails();
int sizeofDetails = Marshal.SizeOf(u);
}
}
}
当我执行代码时,我期待sizeofDetails应该是128.但我得到64.
声明数组是否有任何问题。有人可以帮忙吗?
解决方案
为什么你期望它是128字节?详细信息是类
,而不是struct
,因此Details元素数组将是对元素的引用数组,不是元素本身。
因为你使用64位系统,每个引用是8个字节,所以每个数组是8 * 8字节== 64字节。
您可能会尝试将详细信息设为struct
:然后它是一个值类型,数组将直接包含元素而不是元素的引用。
I dont know if previously someone asked the same. When i tried to search in the net, i couldn't find it. Please help me in solving this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
public class Details
{
public uint ID;
public uint state;
public uint country;
public uint place;
}
[StructLayout(LayoutKind.Sequential)]
public class UserDetails
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=8)]
public Details[] userDetails;
}
static void Main(string[] args)
{
UserDetails u = new UserDetails();
int sizeofDetails = Marshal.SizeOf(u);
}
}
}
When i executed the code, i am expecting the sizeofDetails should be 128. But i am getting 64.
Is there any problem in declaration of the array. Can someone please help?
解决方案
Why would you expect it to be 128 bytes? Details is aclass
, not astruct
so an array of Details elements will be an array of references to the elements, not the elements themselves.
Since you are using a 64 bit system, each reference is 8 bytes, and so each array is 8 * 8 bytes == 64 bytes.
You might try making Details astruct
instead: then it's a value type and the array will directly contain the elements instead of references to the elements.
这篇关于在托管C#中声明结构数组的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文