在另一个属性设置器中使用属性值

Yoa*_*oav 2 c# properties .net-3.5

Class需要property根据另一个设置一个值:

public class Quantities
{
    private int _quant;
    public int Quant
    {
        get { return _quant; }
        set
        {
            if (Unit == "K")
            {
                _quant = value / 1000;
            }
            else
            {
                _quant = value;
            }
        }
    }
    public string Unit { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

根据我做的几个测试,它工作正常,但我仍然不知道这样做是否安全.
是否有可能在编译器(或JIT)知道它应该分配第一个Quant Property之前进行评估?Unit PropertyUnit Property

Dan*_*rth 8

这与编译器或JIT无关.您的代码会分配值.需要知道它们的分配顺序.

顺便说一句:你的代码表现出时间耦合.最好Unit通过创建属性readonly并提供需要单元的构造函数来使至少不可更改:

public class Quantities
{
    private readonly string _unit;
    private int _quant;

    public Quantities(string unit)
    {
        if(unit == null) throw new ArgumentNullException("unit");
        _unit = unit;
    }

    public int Quant
    {
        get { return _quant; }
        set
        {
            if (Unit == "K")
            {
                _quant = value / 1000;
            }
            else
            {
                _quant = value;
            }
        }
    }
    public string Unit { get { return _unit; } }
}
Run Code Online (Sandbox Code Playgroud)

现在不能以错误的方式使用此类.

有关课程可以改进的更多要点,请参阅Lasse的答案.


ang*_*son 6

此类外部的代码必须知道此依赖关系,否则您可能会在Unit没有重新设置的情况下冒险进行更改Quant:

var x = new Quantities(); // why no constructor for this?
x.Unit = "K";
x.Quant = 1700;           // why int? this will now be 1, not 1.7
x.Unit = "M";
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会使该类成为一个结构,并使其成为不可变的:

public struct Quantity
{
    private readonly double _Value;
    private readonly string _Unit;

    public Quantity(double value, string unit)
    {
        _Value = value;
        _Unit = unit;
    }

    public double Value
    {
        {
            return _Value;
        }
    }

    public double Unit
    {
        {
            return _Unit;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,我根本没有更改该值,因此:

var x = new Quantity(1700, "K");
Run Code Online (Sandbox Code Playgroud)

意味着1700K,而不是1.7K.我不会对数据进行这种"自动化"解释.如果您需要使用不同的单位显示值,我会建立一个转换系统:

    public Quantity ConvertToUnit(string newUnit)
    {
        var newValue = ... calculate value with new unit
        return new Quantity(newValue, newUnit);
    }
Run Code Online (Sandbox Code Playgroud)