未分配的属性会占用类中的内存吗? [英] Do unassigned properties take up memory in a class?

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

问题描述

这可能是一个菜鸟问题,但无论如何我还是要问.考虑以下两个类

This might be a bit of a noob question, but I need to ask it anyway. Consider the following two classes

public class Book{
    public string Title;
    public string Author;
    public string ISBN;
    public DateTime Published;
    public string Description;
    public string Genre;
    public float Price
    public int Pages;

    public Book(){
    }
}

public class BookStub{
    public string Title;
    public string Author;

    public BookStub(){
    }        
}

如果我以以下方式创建每个类的实例

If I create an instance of each class in the following way

Book a = new Book{ 
    Title = "Do Androids Dream of Electric Sheep?", 
    Author = "Philip K. Dick" 
};

BookStub b = new BookStub{ 
    Title = "Do Androids Dream of Electric Sheep?", 
    Author = "Philip K. Dick" 
};

这两个实例占用的内存量是否相同?还是第一个占用更多?

Do both of these instances take up the same amount of memory? Or does the first one take up more?

推荐答案

BookStub类的实例相比,Book类的实例将消耗更多的内存,因为当对象被分配时,所有成员变量所需的内存都被分配了.首先创建.

Instances of the Book class will consume more memory than instances of the BookStub class because the memory required for all member variables is allocated when an object is first created.

这是必要的,因为您可以随时写

This is necessary because at any time you could write

a.Price = 12.74F;

设置Price字段的值.如果尚未分配内存,则此代码将失败.

to set the value of the Price field. If the memory had not been allocated, this code would fail.

对于类型为BookStub的对象b,这种故障是不可能的,因为它没有Price字段.编译器将很容易检测到该错误.

Such failure is not possible for object b of type BookStub, because it has no Price field. The compiler would easily detect that error.

因此,要明确回答您的问题:是的,未分配的属性仍然会消耗类的每个实例的内存.只需将它们自动自动初始化为其默认值即可.

So, to answer your question explicitly: yes, unassigned properties still consume memory for each instance of a class. They are simply initialized automatically to their default values.

但是,请注意,只有对于对象的每个实例都必须存在的成员变量才是这种情况.静态字段和所有类型的方法(实例或静态)都与类本身相关联,并且每次创建新实例时都不会占用任何额外的内存.因此,随时添加其他方法和静态字段,而不必担心增加内存占用.

Note, however, that this is only the case for member variables that must exist for each instance of an object. Both static fields and all types of methods (instance or static) are associated with the class itself and do not consume any additional memory each time a new instance is created. So feel free to add additional methods and static fields without worrying about increasing your memory footprint.

这篇关于未分配的属性会占用类中的内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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