C#反射机制

公司项目用到了反射,本人之前从未使用过,查阅资料,自己写写,竟然能跑通,遂,分享。至于原理,百度去。

新建一个类库,里面写个测试类,里面有各种方法,编译过后得到TestReflection.dll


            System.Reflection.Assembly ass = Assembly.LoadFrom("TestReflection.dll"); //加载DLL

            Type type = ass.GetType("TestReflection.BLLService");

            var bll = Activator.CreateInstance(type);//创建实例

            System.Reflection.MethodInfo me = type.GetMethod("StudentInfo");

            me.Invoke(bll,new object[] {"李白",129,DateTime.Now });//这边数组的值需要与方法中的参数位置对应

//这个就是测试类

namespace TestReflection
{
   public class BLLService
    {
        public void GetClassName() {
            Console.WriteLine(this.GetType().Name);
        }
        public void StudentInfo(string name,int age,DateTime datetime) {
            Console.WriteLine(string.Format("学生{0}:\t{1}岁\t生日{2}",name,age,datetime));
        }
    }

}

扫描二维码关注公众号,回复: 3009596 查看本文章

//结果




猜你喜欢

转载自blog.csdn.net/qq_35534449/article/details/80881014