zoukankan      html  css  js  c++  java
  • C#中访问私有成员技巧

    源代码是别人的,你就不能修改源代码,只提供给你dll。或者你去维护别人的代码,源代码却有丢失。这样的情况如果你想知道私有成员的值,甚至去想直接调用类里面的私有方法。那怎么办呢?其实在.net中访问私有成员不是很难,这篇文章提供几个简单的方法让你如愿以偿。

        为了让代码用起来优雅,使用扩展方法去实现。

    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、调用私有方法:

    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);
    }

  • 相关阅读:
    Android关机流程源码分析
    开关机画面
    android camera
    深入分析AIDL原理
    VMware 虚拟机里连不上网的三种解决方案
    查看Linux中自带的jdk ,设置JAVA_HOME
    Hadoop三种模式安装教程(详解)
    Java ArrayList遍历删除问题
    idea git的使用(四)git建立分支与合并分支
    SpringBoot非官方教程 | 终章:文章汇总
  • 原文地址:https://www.cnblogs.com/jeason1997/p/9264490.html
Copyright © 2011-2022 走看看