zoukankan      html  css  js  c++  java
  • 反射怎样调用另外一个类的私有成员

     一个类的私有成员,本来是不可以给外部调用的。但是在某些特殊情况下,

    我们可能确实须要调用另一个类的私有成员,怎么办呢? 看下面的一个例子就明白了。

    要注意的是:尽量不要这么调有,因为,也许版本升级以后,别人就不再提供这个方法了。

     

    namespace 反射调用私有的成员

    {

        class Program

        {

            static void Main(string[] args)

            {

                Type type = typeof(Class1);

                object obj= Activator.CreateInstance(type);

     

                //调用类库中公有的方法用下面的方法就可以了,但是私有方法就不行了。

                MethodInfo mi= type.GetMethod("heihei");

                mi.Invoke(obj, null);

     

                //调用私有的方法只要加上两个参数就可以了

                MethodInfo mi2 = type.GetMethod("haha", BindingFlags.NonPublic| BindingFlags.Instance);

                mi2.Invoke(obj,null);

     

                Console.Read();

            }

        }

     

    public class Class1

        {

            public void heihei()

            {

                Console.WriteLine("say heihei");

            }

     

            private void haha()

            {

                Console.WriteLine("say haha");

            }

     

            public static void hello()

            {

                Console.WriteLine("say hello");

            }

    }

    }

  • 相关阅读:
    Class constructor FileManager cannot be invoked without 'new' in undefined (line undefined, column undefined)
    vscode插件
    面试题
    使用NPOI读取word表格里面的图片
    Postgresql安装过程记录
    .net Core 新增Area的步骤
    kendo grid上的模版示例
    unicode与string之间的转换
    使用yarn安装puppeteer失败的解决方案
    abp第一篇《框架的下载与mysql数据库的切换》
  • 原文地址:https://www.cnblogs.com/La5DotNet/p/2435431.html
Copyright © 2011-2022 走看看