7

I think this is a very trivial question but I am not able to get a definite answer to it on the net.

I have a class which contains both value types and reference types. Considering the reference types in the class will get instantiated sometime during the execution, how the memory is allocated for each member of such a class? How the pointer is stored and accessed for each of these members? Also which type is created in which memory structure, i.e. stack or heap?

I know this much that if only a variable of value type is used in my code then its value and all the other details like its type, etc are stored in the stack. Similarly if a reference type is instantiated then the actual object is created in the heap and a pointer to this memory location is stored in the stack. But what about value types present inside a class (reference type)? Where are they stored and how are they accessed?

I have given an example of such a class below. An answer in reference to this class will be very helpful.

public class Employee
{
    public int EmpNo { get; set; }
    public string EmpName { get; set; }
    public BankAccDetails AccDetails { get; set; }
}

public class BankAccDetails
{
    //Other properties here
}
4

2 に答える 2

5

しかし、クラス内に存在する値型 (参照型) はどうでしょうか? それらはどこに保存され、どのようにアクセスされますか?

値の型は、宣言された場所に格納されます。あなたの場合、それらはヒープになります。

ただし、C# でのメモリ管理に関する次の記事を参照してください。

値型についての真実 - Eric Lippert

デスクトップ CLR 上の C# の Microsoft 実装では、値がローカル変数またはラムダ メソッドまたは匿名メソッドの閉じたローカル変数ではない一時変数であり、メソッド本体がiterator ブロックであり、ジッタは値を登録しないことを選択します。

スタックは実装の詳細、パート 1 -
.NET の Eric Lippert メモリ - 何をどこに置くか - Jon Skeet

于 2012-08-09T03:59:39.487 に答える
0

They are initialized to their default values, which is 0 for int and float, false for bool, and null for every other data type. Structs are initialized using the default constructor. See also the default keyword to initialize generic types without knowing whether they are simple data types or not.

The object is stored on the heap, with each field having a bit of space, either the value for a value type, or the pointer for other types. They are aligned, which means there might be gaps of space in the object.

于 2012-08-09T03:50:36.003 に答える