zoukankan      html  css  js  c++  java
  • 【原创】.NET中利用反射访问和修改类中的私有成员

    .NET中利用反射访问和修改类中的私有成员

    .NET中的反射技术确实是一种很强大的技术,它能突破类对私有成员的封装而访问到它们,下面给出一个例子。

    下面是设计的一个类,包含一个私有域_test

    using System;

    namespace ClassLibrary1
    {
        public class Set
        {
            private int _test = 10;
            public Set()
            {
            }
            public int Test
            {
                get
                {
                    return _test;
                }
            }
        }

    }

    把上面的类编译成dll文件后,我们再来编写一个类来访问上面的类中的私有域_test,编译以下cs代码,注意要引用上面编译好的dll文件。

    using System;
    using System.Reflection;
    using ClassLibrary1;

    namespace ClassLibrary2
    {
        class App
        {
            static void Main()
            {
                Set myTest = new Set();
                Console.WriteLine("before reflect the field Test is:{0}", myTest.Test);
                Type t = typeof(Set);
                try
                {

                    int readTest = (int)t.InvokeMember("_test", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, myTest, null);
                    Console.WriteLine("get the private field _test is:{0}", readTest);
                    t.InvokeMember("_test", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance, null, myTest, new object[] { 5 });
                    Console.WriteLine("after changed the private field by reflect,Test is:{0}", myTest.Test);
                }
                catch (Exception e)
                {

                    Console.WriteLine(e.Message);
                }
                Console.Read();

            }

        }
    }
    以上测试代码运行后,私有域_test由原来的10被改成了5,这样就利用反射技术直接改变了类中私有成员的值。类似的,还可以用反射的方法来访问类中的其他私有成员,比如私有函数等。

    现在还不知道如何在设计基础类的时候阻止这样的反射操作,因为这样破坏了类的封装性,所以微软应该会有一种策略来限制吧。

    如何禁止利用反射技术访问私有成员这个方法还在摸索中。

  • 相关阅读:
    8.10
    今日头条笔试题 1~n的每个数,按字典序排完序后,第m个数是什么?
    Gym 100500B Conference Room(最小表示法,哈希)
    CodeForces 438D The Child and Sequence(线段树)
    UVALIVE 6905 Two Yachts(最小费用最大流)
    Gym Conference Room (最小表示法,哈希)
    hdu 2389 Rain on your Parade(二分图HK算法)
    Codeforces Fox And Dinner(最大流)
    zoj 3367 Counterfeit Money(dp)
    ZOJ3370. Radio Waves(2-sat)
  • 原文地址:https://www.cnblogs.com/absolute8511/p/1649658.html
Copyright © 2011-2022 走看看