gpt4 book ai didi

c# - 通过属性重新分配结构的成员变量

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:34 24 4
gpt4 key购买 nike

所以我有一个按以下方式定义的结构:

    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;放; },作业完美无缺。

有人知道这是怎么回事吗?这是结构的一个怪癖,可以很好地与类一起工作吗?

最佳答案

您在 _weight 属性的 set 方法中递归调用了 _weight 属性。

关于c# - 通过属性重新分配结构的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11712786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com