vendredi 5 février 2016

Get name and value of static class properties using Expression Trees

I have a generic method which compares 2 properties, if value are different it logs the changes and Saves.

    private void SaveIfChanged<T>(Expression<Func<T>> expression, T newValue)
            {

                var expr = (MemberExpression)expression.Body; 
                var obj = (MemberExpression)expr.Expression; 
                var fieldsOfObj = (ConstantExpression)obj.Expression;
                var valuesOfAllFieldsOfObj = ((FieldInfo)obj.Member).GetValue(fieldsOfObj.Value); 

                var propertyInfo = ((PropertyInfo)expr.Member); 
                var oldPropertyValue = propertyInfo.GetValue(valuesOfAllFieldsOfObj, null); 

                if (oldPropertyValue.Equals(newValue)) return;       


 var desctiptionAttributes = (DescriptionAttribute[])propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                Log("{0} changed from {1} to {2}",desctiptionAttributes[0].Description, oldPropertyValue, newValue);
                propertyInfo.SetValue(valuesOfAllFieldsOfObj, newValue, null);

                Save();
            }

It works fine when I pass Properties which are members of a non-static class, but when I pass a static property then it doesn't work.

SaveIfChanged(() => _settings.DomainName, DomainName); // Works
SaveIfChanged(() => Settings.DomainName, DomainName);  //Doesn't work

I also know how to get fields/properties of static class, but only when I have the class name. I just don't know how can I combine the following with my method.

        Type s= typeof(Settings);
        FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);

        foreach (FieldInfo fi in fields)
        {
            Console.WriteLine(fi.Name);
            Console.WriteLine(fi.GetValue(null).ToString());
        }

Thank you.





Aucun commentaire:

Enregistrer un commentaire