C#反射学习1

System.Reflection命名空间
(1) AppDomain:应用程序域,可以将其理解为一组程序集的逻辑容器
(2) Assembly:程序集类
(3) Module:模块类
(4) Type:使用反射得到类型信息的最核心的类
一个AppDomain可以包含N个Assembly,一个Assembly可以包含N个Module,而一个Module可以包含N个Type

1、先编译了一个类库ReflectDll 代码如下:

namespace ReflectDllOne
{
    public class RelClassOne
    {
        public string StringOne()
        {
            return "I am relClassOne.StringOne with no parm";
        }

        public string StringOne(string parm)
        {
            return "I am relClassOne.StringOne with parm " + parm;
        }

        public static string StringOneStatic()
        {
            return "I am relClassOne static";
        }
    }
}

namespace ReflectDllTwo
{
    public class RelClassTwo
    {
        public string StringTwo()
        {
            return "I am relClassTwo.StringOne with no parm";
        }

        public static string StringTwo(string parm)
        {
            return "I am relClassTwo.StringOne with parm" + parm;
        }

        public static string StringTwoStatic()
        {
            return "I am relClassTwo static";
        }
    }
}

 2、使用反射调用ReflectDll中的方法 :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ReflectTest
{
    class Program
    {
        Assembly ass;
        Type type;
        object obj;

        public void ShowReflect()
        {
            ass = Assembly.LoadFile(@"G:\MyProject\ReflectTest\ReflectDll\ReflectDll\bin\Debug\ReflectDll.dll");//反射dll地址
            type = ass.GetType("ReflectDllOne.RelClassOne");//反射的类  命名空间+类名

            System.Reflection.MethodInfo method = type.GetMethod("StringOne",new Type[] {typeof(string)} ); //使用反射程序集中的方法 其中type数组中的项的个数是由要调用的方法的参数个数来决定的。如果无参数,则new Type[]{}
            obj = ass.CreateInstance("ReflectDllOne.RelClassOne");//CreateInstance()一定是命名空间.类名,否则创建的实例为空
            string str = (string)method.Invoke(obj, new string[]{"test"});//method.Invoke获取的是对象类型  需转换为相应类型
            Console.Write(str);
            Console.ReadLine();

            method = type.GetMethod("StringOne", new Type[] { }); //使用反射程序集中的方法  这里因为ReflectDll.RelClassOne中的StringOne方使用了重载  所以必须做处理 用来明确到底使用了哪个方法
            obj = ass.CreateInstance("ReflectDllOne.RelClassOne");
            str = (string)method.Invoke(obj, null);//这个语法个人理解为:调用obj(即ReflectDllOne.RelClassOne类)的方法method(即StringOne) 参数为空(本处调用的StringOne为无参数的重载 与上文中使用的StringOne对应)
            Console.Write(str);
            Console.ReadLine();

            method = type.GetMethod("StringOneStatic", new Type[] { }); 
            obj = ass.CreateInstance("ReflectDllOne.RelClassOne");
            str = (string)method.Invoke(null, null);
            Console.Write(str);
            Console.ReadLine();

        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.ShowReflect();
        }
    }
}

 

posted @ 2012-04-22 21:07  sidihu  阅读(177)  评论(0编辑  收藏  举报