.Net反射

.Net 反射


这个大兄弟写得不要太好啦!(●'◡'●),点击我去看这个大兄弟写的C#反射。

自己理解的反射,通过简单的程序了解基本的反射调用。

//加载需要反射调用的程序集
Assembly ass = Assembly.LoadFile(@"D:xuxuzhaozhao@LearnC#addinDebugxuxuzhaozhao.dll");
//通过该程序集的 *namespace.class* 创建该程序集的实例
object obj=ass.CreateInstance("xuxuzhaozhao.Add");
//获得该示例的类型
Type t=obj.GetType();

//有返回值且有参数的方法
MethodInfo info = t.GetMethod("addd");
object sum = info.Invoke(obj, new object[] { 1, 4 });
Console.WriteLine(sum);

//无返回值且无参数的方法
MethodInfo info2 = t.GetMethod("add");
Console.WriteLine(info2.Invoke(obj,null));

以下是xuxuzhaozhao.dll

namespace xuxuzhaozhao
{
    public class Add
    {
        //无参无返回且为静态方法
        public static void add()
        {
            int i = 1;
            int j = 2;
            Console.WriteLine(i+j);
        }
        //有参有返回且为非静态方法
        public int addd(int x,int y)
        {
            int sum = x + y;
            return sum;
        }
    }
}
原文地址:https://www.cnblogs.com/xuxuzhaozhao/p/6397014.html