【原创】.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,这样就利用反射技术直接改变了类中私有成员的值。类似的,还可以用反射的方法来访问类中的其他私有成员,比如私有函数等。

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

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

posted on 2008-03-02 09:54  absolute  阅读(536)  评论(0编辑  收藏  举报

导航