维护一个包含属性字典的类

时间:2017-03-07 01:01:25

标签: c# linq reflection

我需要设计一个类,其中类的每个属性都在类本身的ObservableDictionary中添加和更新。

这是我提出的代码。

class Win32_DiskDrive : INotifyPropertyChanged
{
    private readonly string _classname = "Win32_DiskDrive";

    public string ClassName
    {
        get
        {
            return _classname;
        }
    }

    private string _caption;

    public string Caption
    {
        get
        {
            return _caption;
        }

        set
        {
            if ((value != _caption) || (value != null))
            {
                _caption = value;
                UpdateDictionary();
                OnPropertyChange();
            }                
        }
    }        

    private string _serialNo;

    public string SerialNumber
    {
        get
        {
            return _serialNo;
        }
        set
        {
            if ((value != _serialNo) || (value != null))
            {
                _serialNo = value;
                UpdateDictionary();
                OnPropertyChange();
            }
        }
    }

    private IDictionary<string,string> _diskDriveProperties = new ObservableDictionary<String, String>();

    public IDictionary<string, string> PropertiesDictionary
    {
        get
        {
            return _diskDriveProperties;
        }

        private set
        {
            _diskDriveProperties = value;
        }                        
    }

    private void UpdateDictionary([CallerMemberName] string propertyname = null)
    {
        _diskDriveProperties[propertyname] = this.GetType().GetProperty(propertyname).GetValue(this).ToString();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChange([CallerMemberName] string propertyname = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }
}

有没有办法使用Linq实现这个没有反射的类?

0 个答案:

没有答案