利用反射在控制台中调用同一解决方案类库中的方法

来源:互联网 发布:传智播客软件测试视频 编辑:程序博客网 时间:2024/05/19 19:34

类库中的方法

using System;namespace WebTest{    public class ReflectTest    {        public ReflectTest()        { }        public string WriteString(string s)        {            return "欢迎您," + s;        }        public static string WriteName(string s)        {            return "欢迎您光临," + s;        }        public string WriteNoPara()        {            return "您使用的是无参数方法";        }        public string saygood()        {            return "good";        }    }}


 

控制台中的反射调用

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication2{    class Program    {        static void Main(string[] args)        {            System.Reflection.Assembly ass;            Type type;            object obj;            try            {                ass = System.Reflection.Assembly.LoadFile(@"D:\Program\ConsoleApplication2\WebTest\bin\Debug\WebTest.dll");//将类库引入该页面                type = ass.GetType("WebTest.ReflectTest");//必须使用名称空间+类名称:比如这里的WebTest就是名称空间,ReflectTest就是类名称                System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法名称                obj = ass.CreateInstance("WebTest.ReflectTest");//必须使用名称空间+类名称                string s = (string)method.Invoke(obj, new string[] { "zhoudanyan" });//实例方法的调用                Console.Write(s + "<br>");                Console.ReadLine();                method = type.GetMethod("WriteName");//方法的名称                s = (string)method.Invoke(obj, new string[] { "zhoudanyan"});                Console.WriteLine(s + "<br>");                Console.ReadLine();                method = type.GetMethod("WriteNoPara");                s = (string)method.Invoke(obj, null);                Console.WriteLine(s+"<br>");                Console.ReadLine();                method = type.GetMethod("saygood");                s = (string)method.Invoke(obj, null);                Console.WriteLine(s+"!");                Console.ReadLine();            }            catch (Exception ex)            {                Console.Write(ex + "<br>");                Console.ReadLine();            }            finally            {                ass = null;                type = null;                obj = null;            }        }    }}


 

原创粉丝点击