I use very similar loops to iterate through all open fields and properties of any passed object. I determine if a field / property is decorated with a specific user attribute; if so, an action is taken on the value of the field or property. Two loops are needed because the method of getting the field value is different from the method to get the value of the property.
I would like to put the loop in one general method so that I can write instead, easier:
DoEachMember(obj.GetType().GetFields()); DoEachMember(obj.GetType().GetProperties());
This requires DoEachMember() to accept the MemberInfo type (which is the parent type of both FieldInfo and PropertyInfo ). The problem is that there is no GetValue method in the MemberInfo class. Both FieldInfo and PropertyInfo use different methods to get the field / property value:
public void DoEachMember(MemberInfo mi, object obj) { foreach (MemberInfo mi in obj.GetType().GetProperties()) { object value mi.GetValue(obj);
Thus, I declare the delegate to use inside the loop, which takes MemberInfo and returns the value of this element as an object:
Question
How to determine the type of objects in the members[] array to determine the delegate used inside the loop? I am currently using the first element of the array, members[0] . Is this a good design?
public void DoEachMember(MemberInfo[] members, object obj) {
Alternatively, I could determine the type at each iteration, but there should be no reason why the individual members of the array will ever differ:
foreach (MemberInfo mi in members) {
c #
Kevin P. Rice
source share