Business logic class

前端 未结 1 972
面向向阳花
面向向阳花 2021-02-09 12:16

I have come across a few ways to write a business logic in asp.net but I am wondering for 2 example below, what are the benefits of using a struct to store class variables:

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 12:27

    As dsimcha states in their answer here:

    Whenever you don't need polymorphism, want value semantics, and want to avoid heap allocation and the associated garbage collection overhead. The caveat, however, is that structs (arbitrarily large) are more expensive to pass around than class references (usually one machine word), so classes could end up being faster in practice.

    As JoshBerke states in his answer here:

    Use a struct when you want value semantics as opposed to reference semantics.

    From the http://msdn.microsoft.com/en-us/library/ms228593.aspx

    1.7 Structs

    Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

    Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs. For example, the following program creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated—one for the array and one each for the 100 elements.

    0 讨论(0)
提交回复
热议问题