Get properties from derived class in base class

前端 未结 7 2234
面向向阳花
面向向阳花 2021-02-09 07:02

How do I get properties from derived class in base class?

Base class:

public abstract class BaseModel {
    protected static readonly Dictionary

        
相关标签:
7条回答
  • 2021-02-09 07:32

    Okay, I solved this problem slightly different than the author of this post: http://weblogs.asp.net/marianor/archive/2009/04/17/wpf-validation-with-attributes-and-idataerrorinfo-interface-in-mvvm.aspx

    public abstract class BaseModel : IDataErrorInfo {
        protected Type _type;
        protected readonly Dictionary<string, ValidationAttribute[]> _validators;
        protected readonly Dictionary<string, PropertyInfo> _properties;
    
        public BaseModel() {
            _type = this.GetType();
            _properties = _type.GetProperties().ToDictionary(p => p.Name, p => p);
            _validators = _properties.Where(p => _getValidations(p.Value).Length != 0).ToDictionary(p => p.Value.Name, p => _getValidations(p.Value));
        }
    
        protected ValidationAttribute[] _getValidations(PropertyInfo property) {
            return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
        }
    
        public string this[string columnName] {
            get {
                if (_properties.ContainsKey(columnName)) {
                    var value = _properties[columnName].GetValue(this, null);
                    var errors = _validators[columnName].Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage).ToArray();
                    return string.Join(Environment.NewLine, errors);
                }
    
                return string.Empty;
            }
        }
    
        public string Error {
            get { throw new NotImplementedException(); }
        }
    }
    

    Maybe it will help somebody.

    0 讨论(0)
提交回复
热议问题