[英]struct instance as member of class C#
I feel completely lost in the logic of the following example code:我完全迷失在以下示例代码的逻辑中:
namespace StructInClass
{
internal class Program
{
static void Main(string[] args)
{
SomeClass someClass = new SomeClass();
someClass.DoStaff();
}
}
public class SomeClass
{
private SomeStruct _someStruct;
public SomeClass() =>
_someStruct = new SomeStruct();
public void DoStaff() =>
_someStruct = new SomeStruct(4, 5);
}
public readonly struct SomeStruct
{
public readonly int x;
public readonly int y;
public SomeStruct()
{
this.x = 0;
this.y = 1;
}
public SomeStruct(int x, int y)
{
this.x = x;
this.y = y;
}
}
}
I have several questions here.我在这里有几个问题。
SomeClass
its SomeStruct
instance will be placed in Heap (meanwhile pointer for this struct instance lies in Stack)?SomeClass
的实例时,它的SomeStruct
实例将被放置在堆中(同时这个结构实例的指针位于堆栈中)?someClass.DoStaff()
new instance of SomeStruct
is created within corresponding stack frame of DoStuff
method, right?someClass.DoStaff()
时, SomeStruct
的新实例是在DoStuff
方法的相应堆栈框架中创建的,对吗? Then pointer now points to new struct instance in Stack?SomeStruct
type in terms of perfomance?SomeStruct
类型的私有字段有什么意义吗? Googling gives me ambiguous answers.谷歌搜索给了我模棱两可的答案。
#1. #1。 SomeClass is on the heap, the struct is inline in that heap memory (if SomeStruct was a class then it would be in a separate hea allocation)
SomeClass 在堆上,结构在该堆 memory 中内联(如果 SomeStruct 是 class 那么它将在单独的堆分配中)
#2 no - its on the heap #2 不 - 它在堆上
#3 - yes its inlined in the containing class as opposed to being a new heap allocation #3 - 是的,它内联在包含的 class 中,而不是新的堆分配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.