What's the difference between struct and class in .NET?

前端 未结 19 1398
一向
一向 2020-11-22 01:51

What\'s the difference between struct and class in .NET?

19条回答
  •  逝去的感伤
    2020-11-22 02:14

    Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.

    Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.

    The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.

提交回复
热议问题