簡體   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