C#中访问私有成员技巧
源代碼是別人的,你就不能修改源代碼,只提供給你dll。或者你去維護別人的代碼,源代碼卻有丟失。這樣的情況如果你想知道私有成員的值,甚至去想直接調(diào)用類里面的私有方法。那怎么辦呢?其實在.net中訪問私有成員不是很難,這篇文章提供幾個簡單的方法讓你如愿以償。
??? 為了讓代碼用起來優(yōu)雅,使用擴展方法去實現(xiàn)。
?
1、得到私有字段的值:
public static T GetPrivateField<T>(this object instance, string fieldname) {BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;Type type = instance.GetType();FieldInfo field = type.GetField(fieldname, flag);return (T)field.GetValue(instance); }2、得到私有屬性的值:
public static T GetPrivateProperty<T>(this object instance, string propertyname) {BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;Type type = instance.GetType();PropertyInfo field = type.GetProperty(propertyname, flag);return (T)field.GetValue(instance, null); }3、設置私有成員的值:
public static void?SetPrivateField(this object?instance,?string?fieldname,?object?value)?
{?
????BindingFlags?flag =?BindingFlags.Instance |?BindingFlags.NonPublic;?
????Type?type = instance.GetType();?
????FieldInfo?field = type.GetField(fieldname, flag);?
??? field.SetValue(instance, value);?
}?
4、設置私有屬性的值:?
public static void?SetPrivateProperty(this object?instance,?string?propertyname,?object?value)?
{?
????BindingFlags?flag =?BindingFlags.Instance |?BindingFlags.NonPublic;?
????Type?type = instance.GetType();?
????PropertyInfo?field = type.GetProperty(propertyname, flag);?
??? field.SetValue(instance, value,?null);?
}?
5、調(diào)用私有方法:
public static?T CallPrivateMethod<T>(this object?instance,?string?name,?params object[] param)
{
????BindingFlags?flag =?BindingFlags.Instance |?BindingFlags.NonPublic;
????Type?type = instance.GetType();
????MethodInfo?method = type.GetMethod(name, flag);
????return?(T)method.Invoke(instance, param);
}
轉(zhuǎn)載于:https://www.cnblogs.com/jeason1997/p/9264490.html
總結(jié)
以上是生活随笔為你收集整理的C#中访问私有成员技巧的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿里云 fatal: Authenti
- 下一篇: IntelliJ IDEA学习记录