リフレクション
最近WPFを触っています。
が、ほしいフィールドやプロパティがプライベートだったりして歯がゆい思いをよくしてます。
気に入らないのでリフレクションで持ってきてしまいましょう。
.NET FOLLOWER » C#: How to set or get value of a private or internal property through the Reflection
リフレクションに便利な拡張メソッド
public static class ReflectionHelper { private static PropertyInfo GetPropertyInfo(Type type, string propertyName) { PropertyInfo propInfo = null; do { propInfo = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); type = type.BaseType; } while (propInfo == null && type != null); return propInfo; } public static object GetPropertyValue(this object obj, string propertyName) { if (obj == null) throw new ArgumentNullException("obj"); Type objType = obj.GetType(); PropertyInfo propInfo = GetPropertyInfo(objType, propertyName); if (propInfo == null) throw new ArgumentOutOfRangeException("propertyName", string.Format("Couldn't find property {0} in type {1}", propertyName, objType.FullName)); return propInfo.GetValue(obj, null); } public static void SetPropertyValue(this object obj, string propertyName, object val) { if (obj == null) throw new ArgumentNullException("obj"); Type objType = obj.GetType(); PropertyInfo propInfo = GetPropertyInfo(objType, propertyName); if (propInfo == null) throw new ArgumentOutOfRangeException("propertyName", string.Format("Couldn't find property {0} in type {1}", propertyName, objType.FullName)); propInfo.SetValue(obj, val, null); } }