What does the keyword “new” do to a struct in C#?

前端 未结 6 1823
傲寒
傲寒 2020-11-28 04:41

In C#, Structs are managed in terms of values, and objects are in reference. From my understanding, when creating an instance of a class, the keyword new causes

6条回答
  •  情话喂你
    2020-11-28 05:13

    Any time an object or struct comes into existence, all of its fields come into existence as well; if any of those fields are struct types, all nested fields come into existence as well. When an array is created, all of its elements come into existence (and, as above, if any of those elements are structs, the fields of those structs also come into existence). All of this occurs before any constructor code has a chance to run.

    In .net, a struct constructor is effectively nothing more than a method which takes a struct as an 'out' parameter. In C#, an expression which calls a struct constructor will allocate a temporary struct instance, call the constructor on that, and then use that temporary instance as the value of the expression. Note that this is different from vb.net, where the generated code for a constructor will start by zeroing out all fields, but where the code from the caller will attempt to have the constructor operate directly upon the destination. For example: myStruct = new myStructType(whatever) in vb.net will clear myStruct before the first statement of the constructor executes; within the constructor, any writes to the object under construction will immediately operate upon myStruct.

提交回复
热议问题