C# 使用正确的属性类型

C# 使用正确的属性类型,c#,properties,C#,Properties,我目前正在创建一个需要使用某些属性的程序。然而,我觉得我目前使用的属性可能不是最好的 以下是我当前使用的属性: // Returns the product name. public string ProductName { get; set; } // Returns and sets the latest price. public decimal LatestPrice { get; set; } // Returns the quantity public

我目前正在创建一个需要使用某些属性的程序。然而,我觉得我目前使用的属性可能不是最好的

以下是我当前使用的属性:

// Returns the product name.
public string ProductName { get; set; }            

// Returns and sets the latest price. 
public decimal LatestPrice { get; set; }

// Returns the quantity
public int Quantity { get; set; }

// returns the total price of all the order items. (latest price * quantity)
public decimal TotalOrder { get; set; }
我觉得那些只返回某些内容的属性,例如
ProductName
属性,应该使用不包含
集的编码属性

或者,如果我将它们设置为
专用集
,会发生什么情况?这有用吗

我可以使用这些属性吗,还是应该对它们进行编码


实际上,我没有收到任何错误代码,只是认为有一种方法可能比我目前的做法更好。

如果属性只返回某些内容,您可以将set accessor设置为private,就像您提到的那样

但是,它不能通过属性设置数量和价格。你需要把它交给Constructor

对于TotalOrder,您应该实现get访问器,使其与更新的最新价格和数量保持一致

class Book
{
     public Book(decimal price, int number)
     {
         LatestPrice  = price;
         Quantity  = number;
     }
    public decimal LatestPrice { get; private set; }
    public int Quantity { get; private set; }
    public decimal TotalOrder { get{ return LatestPrice * Quantity;} private set{}}
}

属性,或者它们的只读性,或者它们的setter是私有的,本质上是没有“用处”的。这完全取决于你想要实现什么。例如,设置计算属性(例如
TotalOrder
)没有任何意义。它应该是只读的,您需要在getter中计算
LatestPrice*Quantity
ProductName
的setter是否应该是私有的取决于谁可以定义产品名称。一般来说,拥有大量带有{get;set;}的公共属性可能是一个面向对象的设计错误。除非您处理的是某种数据传输对象(DTO)。我唯一清楚的一点是,
TotalOrder
应该根据
数量和
最新价格计算,而不是作为一个独立属性。我们几乎没有足够的上下文来知道其余的是否应该是只读的。@Shaq p:也许MSDN的文章可以帮你一点忙。在适当的情况下,属性具有特定的用例(主要是按照约定);有时,应首选方法。你能给你的答案添加一个解释吗?你想用那个(格式错误的)代码块说什么?2.回复:
TotalOrder
:空的私有setter是完全多余的。如果希望属性是只读的,只需完全省略setter即可。3.你为什么建议
数量
最新价格
有一个私人设定者?4.那么
ProductName
呢?为什么要省略它?我对C#比较陌生,从我对属性的记忆中,我感觉那些属性的自动实现代码不会很好地为我服务。对于上述所有属性。我将使用他们的方法,我将继续编码。我在代码中添加了代码,以显示我目前所做的事情,因为我不完全确定如何解释这一切。但它们都将用于从另一个类中获取它们的“值”。我已经创建了我的构造函数