This code is within a ViewModelBase class. I have a custom attribute defined that is meant to trigger methods when a property is changed. The following runs as the ViewModel is being constructed. The idea is to catalog the methods that should be triggered upon a property changed event based on the property name.
It works but I was wondering if there was a way to more efficiently identify methods with the custom attribute, since there are a lot of methods to loop through and generally only one or two methods that have the sought-after attribute.
ExecuteOnPropertyChangedMap = new Dictionary<string, List<MethodInfo>>();
foreach (var method in this.GetType().GetMethods(
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
{
var execAttributes = method.GetCustomAttributes(typeof(ExecuteOnPropertyChangedAttribute), true);
foreach (ExecuteOnPropertyChangedAttribute execAttribute in execAttributes)
{
if (execAttribute == null) continue;
foreach (string propertyName in execAttribute.PropertyNames)
{
if (!ExecuteOnPropertyChangedMap.ContainsKey(propertyName))
ExecuteOnPropertyChangedMap.Add(propertyName, new List<MethodInfo>());
ExecuteOnPropertyChangedMap[propertyName].Add(method);
}
}
}