首页 > 解决方案 > C# 访问属性中的属性?

问题描述

我正在尝试通过使用属性的 Exercism C# 练习“称重机”中的一些测试。我有这些属性:

using System;
enum Units
{
   Pounds,
   Kilograms
}

class WeighingMachine
{
    private decimal inputWeight;
    public decimal InputWeight
    {
        get { return inputWeight; }
        set { if (value >= 0)
                inputWeight = value;
            else throw new ArgumentOutOfRangeException();
        }
    }

    private decimal displayWeight;
    public decimal DisplayWeight
    {
        get
        { return displayWeight; }
        set
        {
            displayWeight = InputWeight - TareAdjustment;
            if (displayWeight <= 0)
                throw new ArgumentOutOfRangeException();
        }
    }

    private decimal _pounds;
   
    public USWeight USDisplayWeight
    {
        get { return _pounds; }
        set { _pounds = new USWeight(InputWeight).Pounds; }
    }

    public decimal TareAdjustment { private get; set; }

    public int Units
    { get; set; }
}

    struct USWeight
    {
        public USWeight(decimal weightInPounds)
        {
            Pounds = (int)weightInPounds;
            Ounces = (weightInPounds - Pounds)*16;
        }
    
        public int Pounds { get; set; }

        public decimal Ounces { get; set; }
    }

我的绊脚石是测试:

[Fact]
public void Get_us_display_weight_pounds()
{
    var wm = new WeighingMachine();
    wm.InputWeight = 60m;
    Assert.Equal(132, wm.USDisplayWeight.Pounds);
}

我无法理解测试如何要求 wm.USDisplayWeight.Pounds - 最后如何访问 .Pounds?就像在 USDisplayWeight 属性中设置了一个属性,但这不可能是吗?我不能让编译器停止抱怨 .Pounds - 我得到“十进制”不包含“磅”的定义,并且找不到接受“十进制”类型的第一个参数的可访问扩展方法“磅”。

我敢肯定这是我在这里忽略的一件简单的事情,但我会很感激任何帮助。

标签: c#properties

解决方案


推荐阅读