c# - 业务逻辑类

标签 c#

我遇到过几种在 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/

相关文章:

c# - 如何观察由于 C# 中另一个等待任务失败而未等待的任务?

c# - C#如何打开一个Word文件并设置相对于项目文件夹的路径

c# - 集合 Entity Framework 5 中的级联更新

c# - 在xaml上将负值显示为正

c# - Dynamics CRM 2011 - 如何在工作流步骤中发送带有外部链接的电子邮件

c# - PayPal 与我的网站集成(我已经阅读过现有帖子)

c# - 连接到 OpenShift 服务

c# - 如何根据路径向 JSON 添加新的 JProperty?

c# - 在c#中将对象转换为字节数组

c# - 如何检查字符串的前两个值