简体   繁体   English

struct c#和与之相关的内存

[英]Struct c# and the memory related to it

given Struct Point : 给定结构点:

public struct Point {
    double x, y;
    Point(double i, double j) {
        x=i;
        y=j;
    }
}

Q1 :whats the diffrence between: Q1 :两者之间的差异是什么?

Point p;

and

Point p=new Point(2.0,3.0);

as i understood it, in the second part annonymous Point struct is being allocated on the heap, and is being copied bit by bit to the p variable's memory allocated on the stack. 据我所知,在第二部分,匿名Point结构正在堆上分配,并被逐位复制到堆栈上分配的p变量的内存中。 am i correct? 我对么?

Q2 :what do i need to do to carry reference to Point instead of allocating it on stack and passing it around by value? Q2 :我需要做什么来携带Point的引用,而不是在堆栈上分配并通过值传递它? (without using unsafe pointers) (不使用不安全的指针)

class Linear {
    private double m, n;
    ref Point p = new Point(2.0,3.0); // not compiling
} 
class Wrapper
{
    public Point Point { get; set; }
}

Using a reference type (class) wrapping a value type (struct) you will allocate it in the heap. 使用包装值类型(struct)的引用类型(类),您将在堆中分配它。

A1: In the first statement you are just declaring the variable, you're not creating an instance of the struct, as you do in the second statement. A1:在第一个语句中,您只是声明变量,您不是像在第二个语句中那样创建结构的实例。

A2: You need to use the REF keyword where you are 'giving' the object to another method, not where you are declaring the variable. A2:您需要使用REF关键字,将对象“提供”给另一个方法,而不是在声明变量的位置。

I usually create a very simple class if I do not want a valuetype struct. 如果我不想要一个valuetype结构,我通常会创建一个非常简单的类。 Which would look soemthing like the code below for your example. 对于你的例子,哪个看起来像下面的代码。 A class will prevent struct boxing/unboxing performance hits in some situations. 在某些情况下,类会阻止struct boxing / unboxing性能命中。 But if you have a List<> of structs it is a single block of memory for all data. 但是如果你有一个List <>结构,它就是所有数据的单个内存块。 With List<> of class you get aa single block of pointers to a lot of class instances. 使用List <>类,您可以获得指向许多类实例的单个指针块。

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Point
{
    public double x, y;

    public Point(double i, double j)
    {
        x = i;
        y = j;
    }
}

In the second statement, an anonymous temporary storage location of type Point is created, most likely on the stack, and it it is passed as an implicit ref parameter to a parameterized constructor. 在第二个语句中,创建了一个类型为Point的匿名临时存储位置,很可能是在堆栈上,并且它作为隐式ref参数传递给参数化构造函数。 After the constructor is complete, the Point variable p is mutated by overwriting each field (public or private) with the corresponding fields in that anonymous temporary, which is then abandoned. 在构造函数完成之后,通过用该匿名临时字段中的相应字段覆盖每个字段(公共或私有)来改变Point变量p ,然后放弃该字段。 Note that the behavior is the same whether or not the struct pretends to be immutable. 请注意,无论struct假装是不可变的,行为都是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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