[备忘]C#之反射篇

     这几天看了不少C#方面的知识,感觉看了之后一段时间后就忘了,特写个备忘,免得忘了又要从头找起.

     定义:Reflection,通过它我们可以在运行时动态获得各种信息,如程序集、模块、类型、字段、属性、方法和事件

 

自己参考资料后写的代码:

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

namespace Refelction
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = "", myword = "";
            Test mytest;
            do
            {
                a = Console.ReadLine().ToString();
                if (a == "1")
                {
                    myword = "test1";
                }
                else
                {
                    myword = "test2";
                }
                Console.WriteLine(myword);
                mytest = (Test)Assembly.Load("Refelction").CreateInstance("Refelction." + myword);
            }
            while (a.ToUpper() != "Y");

            Assembly ass;
            Type type;
            object obj;
            try
            {
                ass = Assembly.LoadFile(@"E:\学习源码\反射\test3\bin\Debug\test3.dll");
                type = ass.GetType("test3.Class1");//必须使用名称空间+类名称
                System.Reflection.MethodInfo method = type.GetMethod("test4");//方法的名称
                obj = ass.CreateInstance("test3.Class1");//必须使用名称空间+类名称
                string s = (string)method.Invoke(obj, new string[] { "\n测试!" }); //实例方法的调用
                Console.WriteLine(s);
                Console.ReadLine();
            }
            catch
            {
               
            }
        }
    }

    public abstract class Test
    {
        public abstract void myprint();
    }

    public class test1 : Test
    {
        public override void myprint()
        {
            Console.WriteLine("this is test1");
        }
    }

    public class test2 : Test
    {
        public override void myprint()
        {
            Console.WriteLine("this is test2");
        }
    }
}

posted @ 2008-10-15 13:54  TerryXu  阅读(334)  评论(0编辑  收藏  举报