繁体   English   中英

C# Class 具有许多属性和类似的设置器,如何重用逻辑

[英]C# Class with many Properties and similar Setters, how to reuse logic

我有一个带有许多属性和公共设置器的 class。 在每个 Setter 上,我想检查值是否已更改,如果更改则调用 EventHandler 方法。 代码最终看起来太长、太重复并且很容易出现程序员错误,因为我可能会在多个 setter 方法上犯一些小错误并搞砸事情。

我想问是否有任何方法可以使此代码更小且更可重用(例如,如果我想添加新的属性):

using System;

public class CosmeticsModel
{
    private string _skin;
    public string Skin {
        get => _skin;
        set
        {
            if (value != _skin)
            {
                _skin = value;
                OnCosmeticChanged("Skin", _skin);
            }
        }
    }

    private string _eyes;
    public string Eyes {
        get => _eyes;
        set
        {
            if (value != _eyes)
            {
                _eyes = value;
                OnCosmeticChanged("Eyes", _eyes);
            }
        }
    }

    private string _mouth;
    public string Mouth {
        get => _mouth;
        set
        {
            if (value != _mouth)
            {
                _mouth = value;
                OnCosmeticChanged("Mouth", _mouth);
            }
        }
    }

    private string _accessory;
    public string Accessory {
        get => _accessory;
        set
        {
            if (value != _accessory)
            {
                _accessory = value;
                OnCosmeticChanged("Accessory", _accessory);
            }
        }
    }

    private string _shoes;
    public string Shoes {
        get => _shoes;
        set
        {
            if (value != _shoes)
            {
                _shoes = value;
                OnCosmeticChanged("Shoes", _shoes);
            }
        }
    }

    private string _hat;
    public string Hat {
        get => _hat;
        set
        {
            if (value != _hat)
            {
                _hat = value;
                OnCosmeticChanged("Hat", _hat);
            }
        }
    }

    private string _oneHandedWeapon;
    public string OneHandedWeapon {
        get => _oneHandedWeapon;
        set
        {
            if (value != _oneHandedWeapon)
            {
                _oneHandedWeapon = value;
                OnCosmeticChanged("OneHandedWeapon", _oneHandedWeapon);
            }
        }
    }

    // [... rest of the Class]
}

您可以提取一个名为SetProperty的方法。 您还可以使用CallerMemberName自动设置属性名称。

private void SetProperty(ref string property, string value, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "") {
    if (value != property)
    {
        property = value;
        OnCosmeticChanged(propertyName, property);
    }
}

用法:

private string _hat;
public string Hat {
    get => _hat;
    set => SetProperty(ref _hat, value);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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