我遇到过几种在 asp.net 中编写业务逻辑的方法,但我想知道下面的 2 个示例,使用结构存储类变量的好处是什么:
namespace Shopping
{
public struct ShoppingCart
{
public string Color;
public int ProductId;
}
public partial class MyShoppingCart
{
public decimal GetTotal(string cartID)
{
}
// Some other methods ...
}
}
namespace Shopping
{
public partial class MyShoppingCart
{
public string Color{ get; set; }
public int ProductId{ get; set; }
public decimal GetTotal(string cartID)
{
}
// Some other methods ...
}
}
最佳答案
正如 dsimcha 在 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.
正如 JoshBerke 在 his answer here 中所说的那样:
Use a struct when you want value semantics as opposed to reference semantics.
来自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.
关于c# - 业务逻辑类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14000609/