如何决定或计算课程的大小 [英] How to decide or calculate size of class

查看:68
本文介绍了如何决定或计算课程的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算课程的大小。



我尝试过:



  class  A 
{

int a;
float f;

public void cal();
public void cal2();

}





这个班级的大小是多少?

如何计算它?



是为功能分配的内存?



是这个声明分配内存还是



 A a =  new  A(); 





会分配一个内存吗?

解决方案

方法在类实例中不占空间(尽管它们可以在EXE文件中占用空间。)

你可以很容易地得到类引用的大小,但是......你不需要,除非你谈到非托管代码 - 而且你的价值get可能相当混乱。

但是......

  int 大小= Marshal.SizeOf( typeof (Myclass)); 

会告诉你。

在你的课上运行:

 [StructLayout(LayoutKind.Sequential)] 
class Myclass
{
int a;
float f;
public void cal(){}
公开 无效 cal2(){}
}



它将会给你8,因为int是4个字节,float是4个字节。但它不会告诉你你的想法!

如果我加入你的班级:

 [StructLayout(LayoutKind.Sequential)] 
class Myclass
{
int a;
float f;
int [] array = new int [ 100000 ];
public void cal(){}
公开 void cal2(){}
}

您认为现在有多大?

答案是16 - 数组占用8个字节!怎么样?因为数组是一个引用,并且像所有类实例一样,所有变量包含的是对实际数据的引用 - 而64位系统上的引用总是8个字节,无论它引用的数据大小如何。


how to calculate size of class.

What I have tried:

class A
{

   int a;
   float f;

  public void cal();
  public void cal2();

}



what is size of this class?
how to calculate it?

is memory allocated for function ?

is this declaration allocate a memory or

A a=new A();



will allocate a memory?

解决方案

Methods take no space in a class instance (although they do take space in the EXE file).
You can get the size of the class quote easily, but ... you don;t need to, except when you talk to unmanaged code - and the value you get is probably rather confusing.
But...

int size = Marshal.SizeOf(typeof(Myclass));

Will tell you.
Run on your class:

[StructLayout(LayoutKind.Sequential)]
class Myclass
    {
    int a;
    float f;
    public void cal() { }
    public void cal2() { }
    }


It will give you "8" because an int is 4 bytes, and a float is 4 bytes. But it won't tell you what you think!
If I add to your class:

[StructLayout(LayoutKind.Sequential)]
class Myclass
    {
    int a;
    float f;
    int[] array = new int[100000];
    public void cal() { }
    public void cal2() { }
    }

How big do you think it will give you now?
The answer is "16" - the array takes 8 bytes! How? Because the array is a reference, and like all class instances all a variable contains is a reference to the actual data - and a reference on a 64 bit system is always 8 bytes, regardless of the size of the data it references.


这篇关于如何决定或计算课程的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆