简体   繁体   中英

Extended GET SET Object

public class ZakazkandDTO
{
    private decimal? _pcPevna;
    private decimal? _sleva;
    
    public decimal? PcPevna 
    { 
        get => _pcPevna;
        set 
        { 
            _pcPevna = value; 
            if (_pcPevna.HasValue) 
                Sleva = PcSpec = 0; 
        }
    }
    
    public decimal? Sleva 
    { 
        get => _sleva; 
        set 
        { 
            _sleva = value; 
            if (_sleva.HasValue) 
                PcPevna = null; 
        }
    }
    
    public decimal? PcSpec { get; set; }
}

This is my DTO object, when i try to set property PcPevna it does not work. why?

Because setting PcPevna to a value != null sets Sleva to 0 and its setter in turn sets PcPevna back to null .

Change the code to

public decimal? PcPevna {
    get => _pcPevna;
    set {
        _pcPevna = value;
        if (_pcPevna.HasValue)
            _sleva = PcSpec = 0;
    }
}

public decimal? Sleva { 
    get => _sleva;
    set {
        _sleva = value;
        if (_sleva.HasValue)
            _pcPevna = null;
    }
}

Ie, set the backing fields directly to avoid triggering the setters of the other properties again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM