类中的属性/方法是否占用内存中的空间? [英] Do properties/methods in classes take space in memory?

查看:481
本文介绍了类中的属性/方法是否占用内存中的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有这样的代码:

  public class Enemy 
{
public int hp;
}

然后一个敌人对象在32位机器中需要4个字节,在64位中需要8个字节(如果我错了,请纠正我)。



如果我们将其更改为如下所示:

  public class敌人
{
public int hp;
public void Attack(){}
}

c> Enemy 对象仍然会采用与之前相同的内存量,对吗?



同样的:

  public class Enemy 
{
private int hp;
public int Hp {get {return hp; } set {hp = value; }}

$ / code>

据我所知,属性是函数,但被当作变量,对吧?



所以,如果我们这样做了:

  public class Enemy 
{
public int Hp {set;得到; }
}

这是否意味着一个 Enemy 对象现在完全不占用内存空间?这是没有任何意义的。



甚至是这个,对于这个问题:

  public class Enemy 
{
public void DoSomething(){}
}

有人可以解释吗?

解决方案

int 在C#中始终是 System.Int32 ,无论32位还是64位应用程序,它总是占用4个字节的空间。



然而,对象中还有额外的开销。 Jon Skeet有一个博客文章,详细介绍了这里的一些内容,内存和字符串

正如您所看到的,即使没有字段,以32位运行时,对象的基本大小也是12个字节。



然而,你是对的,因为具有代码的属性不一定会增加对象的大小。



然而,如果你使它成为一个自动属性,像这样:

  public int Hp {get;组;然后编译器会自动为你创建一个后台字段,以保存该属性的值,将再次占用空间。


If we had code like this:

public class Enemy
{
   public int hp;
}

Then an Enemy object would take 4 bytes in 32-bit machines, and 8 bytes in 64-bit (correct me if I'm wrong).

If we change it to something like this:

public class Enemy
{
   public int hp;
   public void Attack() {}
}

An Enemy object would still take the same amount of memory as it did before, right?

The same for this:

public class Enemy
{
   private int hp;
   public int Hp { get { return hp; } set { hp = value; } }
}

From what I know, a property is function, but treated as a variable, right?

So if we did this:

public class Enemy
{
   public int Hp { set; get; }
}

Does that mean, an Enemy object now takes no memory space at all? That doesn't make any sense.

Or even this, for that matter:

public class Enemy
{
   public void DoSomething() { }
}

Can somebody explain?

解决方案

int in C# is always going to be System.Int32 which will always take up 4 bytes of space, regardless of 32-bit or 64-bit application.

However, there's additional overhead in an object. Jon Skeet has a blogpost that details some of this here, Of memory and strings.

As you can see, the base size of an object is 12 bytes when running as 32-bit, even if you have no fields.

You're right, however, in that a property that has code does not necessarily increase the size of the object.

However, if you make it an auto-property, like this:

public int Hp { get; set; }

Then the compiler will automagically create a backing field for you to hold the value of that property, which will again take up space.

这篇关于类中的属性/方法是否占用内存中的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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