namespace Xaoc.BasicClasses { public static class ReflectionUtil { public static void SetValue (this MemberInfo p_member, object obj, object value) { if (p_member == null || obj == null) throw new Exception ("Invalid parameters"); switch (p_member.MemberType) { case MemberTypes.Field: (p_member as FieldInfo) .SetValue (obj, value); break; case MemberTypes.Property: if ((p_member as PropertyInfo) .CanWrite) (p_member as PropertyInfo) .SetValue (obj, value, null); else throw new Exception ("Property cannot be changed"); break; default: throw new Exception ("MemberTypes incompatible type"); } } public static object GetValue (this MemberInfo p_member, object obj) { if (p_member == null || obj == null) throw new Exception ("Invalid parameters"); object result = null; switch (p_member.MemberType) { case MemberTypes.Field: result = (p_member as FieldInfo) .GetValue (obj); break; case MemberTypes.Property: if ((p_member as PropertyInfo) .CanRead) result = (p_member as PropertyInfo) .GetValue (obj, null); else throw new Exception ("Unable to get property value"); break; default: throw new Exception ("MemberTypes incompatible type"); } return result; } public static Type GetMemberType (this MemberInfo p_member) { if (p_member == null) throw new Exception ("Invalid parameters"); Type result = null; switch (p_member.MemberType) { case MemberTypes.Field: result = (p_member as FieldInfo) .FieldType; break; case MemberTypes.Property: result = (p_member as PropertyInfo) .PropertyType; break; default: throw new Exception ("MemberTypes incompatible type"); } return result; } } }
Source: https://habr.com/ru/post/24828/
All Articles