【发布时间】:2012-07-30 05:01:53
【问题描述】:
所以我有一个按以下方式定义的结构:
public struct Item
{
public string _name { get; set; }
public double _weight
{
get
{
return _weight;
}
set
{
_weight = value;
//Shipping cost is 100% dependent on weight. Recalculate it now.
_shippingCost = 3.25m * (decimal)_weight;
//Retail price is partially dependent on shipping cost and thus on weight as well. Make sure retail price stays up to date.
_retailPrice = 1.7m * _wholesalePrice * _shippingCost;
}
}
public decimal _wholesalePrice
{
get
{
return _wholesalePrice;
}
set
{
//Retail price is partially determined by wholesale price. Make sure retail price stays up to date.
_retailPrice = 1.7m * _wholesalePrice * _shippingCost;
}
}
public int _quantity { get; set; }
public decimal _shippingCost { get; private set; }
public decimal _retailPrice { get; private set; }
public Item(string name, double weight, decimal wholesalePrice, int quantity) : this()
{
_name = name;
_weight = weight;
_wholesalePrice = wholesalePrice;
_quantity = quantity;
}
//More stuff
我在另一个类中也有一个 Item 实例。当我尝试通过以下命令调用 weight 属性时,程序崩溃:
currentUIItem._weight = formattedWeight;
未提供描述性错误。请注意,此时, currentUIItem 已使用无参数默认构造函数进行了更新。现在,这是奇怪的部分。当我删除 weight 的 set 属性的自定义实现并将其替换为通用 { get;放; },作业完美无缺。
有人知道这里发生了什么吗?这是一种可以与类一起正常工作的结构吗?
【问题讨论】:
-
结构应该是不可变的:stackoverflow.com/a/3753640/588868
-
这一切都表明它应该是
class,而不是struct。它不会影响无限递归,但是:值得注意。 -
为什么说这一定是一堂课呢?我读到结构应该是不可变的,但由于我只使用单个线程,我不知道我会如何无意中遇到问题。
-
我不同意它应该是一个类的想法,但我不喜欢结构的设计。只要可行,结构的设计应使其状态可以完全包含在行为合理的公共字段中,并且除了构造函数之外,不应有任何成员修改
this。我将消除_ShippingCost和_RetailPrice字段,而是将它们作为只读属性,根据Weight和WholesalePrice计算,除非您希望允许将零售价显式设置为“覆盖”那个计算。那样的话…… -
...我建议可能有一个具有定义语义的
RetailPriceOverride字段,或者可能使用不可变的结构或类。我通常建议不要使用可变类,因为它们的语义可能很模糊,除非它们的使用方式与可变类非常不同。
标签: c# properties struct