C#反射知识学习

近日对反射知识学习了解,在万能的WWW下,基本有了较为全面的了解。废话少说,直接上代码!!

  • 业务组件类库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BizClassLibrary
{
    [Serializable]
    public class HelloWord
    {
        //公有字段
        public string PublicField = "";

        //私有字段
        private string privateField = "";


        //公有属性
        public string PublicProperty
        {
            get { return this.privateField; }
            set { this.privateField = value; }
        }

        //私有属性
        private string PrivateProperty
        {
            get { return this.privateField; }
            set { privateField = value; }
        }  


        public HelloWord()
        {}

        public HelloWord(string name): base()
        {
            this.privateField = "带参构造函数参数值:"+ name;
        }


        private string PrivateMethod()
        {
            return "私有方法调用测试";
        }

        public static string PublicStaticMethod()
        {
            return "公有静态方法调用测试!";
        }

        public string SimpleNoParamsMethod()
        {
            return "公有无参无重载方法调用测试!" + this.privateField + this.PublicField;
        }

        public string SimpleHaveParamsMethod(string name)
        {
            return "公有有参无重载方法调用测试!参数name(string):" + name;
        }

        public string SayHello()
        {
            return "公有无参重载方法SayHello()调用测试!";
        }

        public string SayHello(string name)
        {
            return "公有单参重载方法SayHello(string name)调用测试!参数name(string):" + name;
        }

        public string SayHello(string name, int times)
        {
            return "公有多参重载方法SayHello(string name, int times)调用测试!参数name(string):" + name + ";参数times(int):" + times.ToString();
        }
    }

    public class MyPrint
    {
        public string PrintInfo()
        {
            return "MyPrint.PrintInfo()";
        }
    }
}

 

  • 调用测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ReflectSample01
{
    class Program
    {
        delegate string TestDelegate(string value, int value1);

        static void Main(string[] args)
        {            
            string assemblyFile = "BizClassLibrary.dll";            
            string assemblyQualifiedFile = AppDomain.CurrentDomain.BaseDirectory + assemblyFile;

            string assemblyName = "BizClassLibrary";
            string typeName = "BizClassLibrary.HelloWord";  //名称空间+类名称

            System.Reflection.Assembly assembly = Assembly.LoadFrom(assemblyQualifiedFile);
            Type type = assembly.GetType(typeName);

            //(建议?)如果动态加载dll类库并建立类的对象用assembly; 如果用remoting或webservice之类的远程对象则用activator;
            Object instance = assembly.CreateInstance(typeName);  //Assembly.CreateInstance内部调用了Activator.CreateInstance
            //Object instance = Activator.CreateInstance(assembly.GetType(typeName));            
            //Object instance = Activator.CreateInstance(type);   //
            //Object instance = Activator.CreateInstance(type, new string[] { "John" }); //带参构造函数初始化
            //Object instance = Activator.CreateInstance(assemblyName, typeName).Unwrap(); 

            Console.WriteLine("----------获取程序集下所有类名 GetTypes()------------");
            foreach (Type t in assembly.GetTypes())
            {
                Console.WriteLine(string.Format("Name:'{0}' \t ModuleName:'{1}'", t.Name, t.Module.Name));
            }

            Console.WriteLine("----------获取程序集下所有模块名 GetModules()------------");
            foreach (Module module in assembly.GetModules())
            {
                Console.WriteLine("module name:" + module.Name);
            }

            Console.WriteLine();

            Console.WriteLine("----------获取程序集类的所有成员 GetMembers()---------");
            foreach (MemberInfo m in type.GetMembers())
            {
                Console.WriteLine(m.Name);
            }

            Console.WriteLine("----------获取程序集类的所有方法 GetMethods()---------");
            foreach (System.Reflection.MethodInfo m in type.GetMethods())
            {
                Console.WriteLine(m.Name);
            }

            Console.WriteLine("----------获取程序集类的所有属性 GetProperties()---------");
            foreach (PropertyInfo m in type.GetProperties())
            {
                Console.WriteLine(m.Name);
            }

            Console.WriteLine("----------获取程序集类的所有字段 GetFields()---------");
            foreach (FieldInfo m in type.GetFields())
            {
                Console.WriteLine(m.Name);
            }

            Console.WriteLine();
            Console.WriteLine("----------反射调用执行测试结果---------");

            #region 构造函数测试
            Console.WriteLine("*********构造函数测试*********");
            {
                Object instanceObj = Activator.CreateInstance(type); //带参构造函数初始化
                MethodInfo method = type.GetMethod("SimpleNoParamsMethod", new Type[] { });//方法
                string s = (string)method.Invoke(instanceObj, null);   //方法调用
                Console.WriteLine(s);
            }

            {
                Object instanceObj = Activator.CreateInstance(type, new string[] { "John" }); //带参构造函数初始化
                MethodInfo method = type.GetMethod("SimpleNoParamsMethod", new Type[] { });//方法
                string s = (string)method.Invoke(instanceObj, null);   //方法调用
                Console.WriteLine(s);                
            }
            #endregion

            #region 字段与属性测试
            Console.WriteLine("*********字段与属性测试*********");
            {
                Object instanceObj = Activator.CreateInstance(type); //带参构造函数初始化
                PropertyInfo pi = type.GetProperty("PublicProperty");
                pi.SetValue(instanceObj, "我设置的公有属性值", null);
                //PropertyInfo pi = type.GetProperty("PrivateProperty", BindingFlags.Instance | BindingFlags.NonPublic);
                //pi.SetValue(instanceObj, "我设置的私有属性值", null);

                MethodInfo method = type.GetMethod("SimpleNoParamsMethod", new Type[] { });//方法
                string s = (string)method.Invoke(instanceObj, null);   //方法调用
                Console.WriteLine(s);
            }

            {
                Object instanceObj = Activator.CreateInstance(type); //带参构造函数初始化
                FieldInfo fi = type.GetField("PublicField");
                fi.SetValue(instanceObj, "我设置的公有字段值");
                //FieldInfo fi = type.GetField("privateField", BindingFlags.Instance | BindingFlags.NonPublic);
                //fi.SetValue(instanceObj, "我设置的私有字段值");

                MethodInfo method = type.GetMethod("SimpleNoParamsMethod", new Type[] { });//方法
                string s = (string)method.Invoke(instanceObj, null);   //方法调用
                Console.WriteLine(s);
            }

            #endregion

            #region 方法调用测试
            Console.WriteLine("*********方法测试*********");
            {
                //私有方法
                MethodInfo method = type.GetMethod("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic);
                string s = (string)method.Invoke(instance, null);
                Console.WriteLine(s);
            }

            {
                MethodInfo method = type.GetMethod("PublicStaticMethod", new Type[] { });//方法
                string s = (string)method.Invoke(null, null);   //静态方法调用
                Console.WriteLine(s);

            }

            {
                MethodInfo method = type.GetMethod("SimpleNoParamsMethod", new Type[] { });//方法
                string s = (string)method.Invoke(instance, null);   //方法调用
                Console.WriteLine(s);
            }

            {
                MethodInfo method = type.GetMethod("SimpleHaveParamsMethod");//方法
                string s = (string)method.Invoke(instance, new string[] { "John" });   //方法调用
                Console.WriteLine(s);
            }

            {
                MethodInfo method = type.GetMethod("SayHello", new Type[] { });//方法的名称,方法有重载时需加参数new Type[]{}
                string s = (string)method.Invoke(instance, null);
                Console.WriteLine(s);
            }

            {
                MethodInfo method = type.GetMethod("SayHello", new Type[] { typeof(System.String) });//方法
                string s = (string)method.Invoke(instance, new string[] { "John" });
                Console.WriteLine(s);
            }

            {
                MethodInfo method = type.GetMethod("SayHello", new Type[] { typeof(System.String), typeof(int) });//方法
                string s = (string)method.Invoke(instance, new object[] { "John", 5 });
                Console.WriteLine(s);
            }
            #endregion

            #region InvokeMember方式
            Console.WriteLine("*********InvokeMember方式测试*********");
            {
                object s = type.InvokeMember("PrivateMethod", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, instance, null);
                Console.WriteLine(s.ToString());
            }

            {
                object s = type.InvokeMember("SimpleHaveParamsMethod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, instance, new string[] { "alice" });
                Console.WriteLine(s.ToString());
            }

            {
                object s = type.InvokeMember("SayHello", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, instance, new object[] { "applo" });
                Console.WriteLine(s.ToString());
            }

            {
                object s = type.InvokeMember("SayHello", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, instance, new object[] { "zeus", 3 });
                Console.WriteLine(s.ToString());
            }
            #endregion

            Console.ReadLine();
        }
    }
}

MSDN参考 http://msdn.microsoft.com/zh-cn/library/vstudio/f7ykdhsy.aspx

转载一篇相关文章 http://www.cnblogs.com/JimmyZhang/archive/2008/03/18/1110711.html

posted @ 2012-11-23 13:33  行野摄色  阅读(564)  评论(0编辑  收藏  举报