代码之家  ›  专栏  ›  技术社区  ›  DannyD

如何在c语言的setter中设置值#

c#
  •  0
  • DannyD  · 技术社区  · 7 年前

    我想添加自定义逻辑,如果我的ulong为0(默认值),它将被设置为1。以下是我所拥有的:

        private ulong quantity;
    
        public ulong Quantity
        {
            get
            {
                return this.quantity;
            }
    
            set 
            {
                if (this.Quantity == 0)
                {
                    this.quantity = 1;
                    return;
                }
    
                this.Quantity = this.quantity;
            }
        }
    

    Parameter 'value' of 'PurchaseForPayoutRequest.Quantity.set(ulong)' is never used

    3 回复  |  直到 7 年前
        1
  •  3
  •   Brendan Green    7 年前

    你需要使用 contextual keyword value

    public ulong Quantity
    {
        get
        {
            return this.quantity;
        }
    
        set 
        {
            if (value == 0)
            {
                this.quantity = 1;
                return;
            }
    
            this.quantity = value;
        }
    }
    
        2
  •  3
  •   TheGeneral    7 年前

    properties 正确地说,您需要使用 value 并确保您正在访问支持字段。您的示例也可以使用 expression body members ?: Operator

    private ulong _quantity;
    
    public ulong Quantity
    {
       get => _quantity;
       set => _quantity = value == 0 ? (ulong)1 : value;
    }
    
        3
  •  0
  •   Dhaval    7 年前

    public ulong quantity
    {
        get
        {
            return this.quantity;
        }
    
        set 
        {
            if (value == 0)
            {
                this.quantity = 1;
                return;
            }
            else
            {
                this.quantity = value;
            }
        }
    }