简体   繁体   English

作为 class C# 成员的结构实例

[英]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.我在这里有几个问题。

  1. Do I correctly understand that when I create an instance of SomeClass its SomeStruct instance will be placed in Heap (meanwhile pointer for this struct instance lies in Stack)?我是否正确理解当我创建SomeClass的实例时,它的SomeStruct实例将被放置在堆中(同时这个结构实例的指针位于堆栈中)?
  2. When I call 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?然后指针现在指向堆栈中的新结构实例?
  3. Is there any sense to declare private field of 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM