C#汇总-反射

版权声明:未经本人允许,必须声明原文转载地址和作者! https://blog.csdn.net/liuchang19950703/article/details/86720969

一:C#动态加载DLL

二:C#动态加载方法

三:C#动态加载属性和字段

1:定义一个泛型People类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assembly_1
{
    public class People
    {

        /// <summary>
        /// 属性
        /// </summary>
        public string name { get; set; }
        public int age { get; set; }

        /// <summary>
        /// 字段
        /// </summary>
        public string fieldName;

        public People()
        {

        }
        public People(string xName)
        {
            this.name = xName;
        }

        public string GetName(string nameStr)
        {
            return (this.name + nameStr);
        }

        #region 测试方法

        public string Show1()
        {
            Console.WriteLine(string.Format("这里是{0}方法", "Show1"));
            return string.Format("这里是{0}方法", "Show1");
        }

        public string Show2(string param)
        {
            Console.WriteLine(string.Format("这里是{0}方法", param));
            return string.Format("这里是{0}方法", param);
        }

        public string Show3(string param, int paramCount)
        {
            Console.WriteLine(string.Format("这里是{0}方法,数量为{1}", param, paramCount));
            return string.Format("这里是{0}方法,数量为{1}", param, paramCount);
        }

        /// <summary>
        /// 私有方法
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        private string Show4(string param)
        {
            Console.WriteLine(string.Format("这里是{0}私有方法", param));
            return string.Format("这里是{0}私有方法", param);
        }

        /// <summary>
        /// 静态方法
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Show5(string param)
        {
            Console.WriteLine(string.Format("这里是{0}静态方法", param));
            return string.Format("这里是{0}静态方法", param);
        }
        #endregion

    }

    /// <summary>
    /// 泛型类和泛型方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Country<T>
    {
        public void GetCountryName<K>(T name, K count)
        {
            Console.WriteLine(string.Format("这是泛型类泛型方法_参数{0},{1}", name, count));
        }

    }

}

2:调用类运行

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ControlDemo.泛型;
using System.Reflection;
using Model;

namespace ControlDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
               #region 反射
            try
            {
                {
                    #region 1.动态加载DLL
                    /*
                     *  1.Load :表示加载当前目录的dll,不带“dll”后缀名
                     *  2.LoadFrom :表示加载当前目录的dll, 带"dll"后缀名 或者 表示加载完成目录的dll,   注:LoadFrom既加载dll的内容,又加载内部引用的内容
                     *  3.LoadFile : 表示加载完成目录的dll,  注:LoadFile只加载dll的内容,不加载内部引用的内容
                     */
                    /*************************加载dll**********************/
                    {
                        //1.加载同级目录的dll
                        Assembly assembly = Assembly.Load("Assembly_1");
                        Type type = assembly.GetType("Assembly_1.People");
                        Assembly_1.People objPeople = Activator.CreateInstance(type, new object[] { "I am " }) as Assembly_1.People;
                        string objReturn = objPeople.GetName("KOBE");
                        Console.WriteLine(objReturn);
                    }
                    {
                        //2.加载外来目录的dll
                        //方法一【错误】:
                        //Assembly assembly = Assembly.LoadFrom(@"C:\Users\MrLIu\Desktop\StudySolution\Model\bin\Debug\Model.dll");
                        ////Assembly assembly = Assembly.LoadFrom("Model.dll");
                        //Type type = assembly.GetType("Model.Common");
                        //Model.Common objCommon = Activator.CreateInstance(type) as Model.Common;
                        ////注意报错:【原因是:两个名字相同路径不同的程序集创建的对象不相同无法转换,引用的Model路径和Model类库的路径不同】
                        ////assembly.loadfile只载入相应的dll文件,比如assembly.loadfile("b.dll"),则载入b.dll,假如b.dll中引用了a.dll的话,a.dll并不会被载入。
                        ////assembly.loadfrom则不一样,它会载入dll文件及其引用的其他dll,比如上面的例子,a.dll也会被载入。
                        //string commonReturn = objCommon.GetName("Jordan");
                        //Console.WriteLine(commonReturn);

                        //方法一【正确】:
                        Assembly assembly = Assembly.LoadFrom("Model.dll");
                        Type type = assembly.GetType("Model.Common");
                        Model.Common objCommon = Activator.CreateInstance(type) as Model.Common;
                        ////注意报错:【原因是:两个名字相同路径不同的程序集创建的对象不相同无法转换,引用的Model路径和Model类库的路径不同】
                        ////assembly.loadfile只载入相应的dll文件,比如assembly.loadfile("b.dll"),则载入b.dll,假如b.dll中引用了a.dll的话,a.dll并不会被载入。
                        ////assembly.loadfrom则不一样,它会载入dll文件及其引用的其他dll,比如上面的例子,a.dll也会被载入。
                        string commonReturn = objCommon.GetName("Jordan");
                        Console.WriteLine(commonReturn);
                    }
                    {
                        //方法二:
                        // 获取程序的基目录。
                        Assembly assembly = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + @"Model.dll");
                        //Assembly assembly = Assembly.LoadFrom("Model.dll");
                        Type type = assembly.GetType("Model.Common");
                        Model.Common objCommon = Activator.CreateInstance(type) as Model.Common;
                        //注意报错:assembly.loadfile只载入相应的dll文件,比如assembly.loadfile("b.dll"),则载入b.dll,假如b.dll中引用了a.dll的话,a.dll并不会被载入。
                        //assembly.loadfrom则不一样,它会载入dll文件及其引用的其他dll,比如上面的例子,a.dll也会被载入。
                        string commonReturn = objCommon.GetName("Jordan");
                        Console.WriteLine(commonReturn);
                    }
                    #endregion
                    #region 2.动态加载DLL的方法
                    {
                        Assembly assembly = Assembly.Load("Assembly_1");
                        Type type = assembly.GetType("Assembly_1.People");
                        //Assembly_1.People classObject = Activator.CreateInstance(type) as Assembly_1.People;
                        object classObject = Activator.CreateInstance(type);
                        {
                            MethodInfo method = type.GetMethod("Show1");
                            method.Invoke(classObject, null);
                        }
                        {
                            MethodInfo method = type.GetMethod("Show2", new Type[] { typeof(string) });
                            method.Invoke(classObject, new object[] { "Show2的参数" });
                        }
                        {
                            MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(string), typeof(int) });
                            method.Invoke(classObject, new object[] { "show3的参数", 1 });
                        }
                        {
                            //私有方法
                            MethodInfo method = type.GetMethod("Show4", BindingFlags.Instance | BindingFlags.NonPublic);
                            method.Invoke(classObject, new object[] { "show4的参数" });
                        }
                        {
                            //静态方法
                            MethodInfo method = type.GetMethod("Show5", new Type[] { typeof(string) });
                            method.Invoke(null, new object[] { "show5的参数" });
                        }
                        {
                            //泛型类和泛型方法
                            Assembly geneAssembly = Assembly.Load("Assembly_1");
                            Type geneType = geneAssembly.GetType("Assembly_1.Country`1");
                            Type geneSecondType = geneType.MakeGenericType(new Type[] { typeof(string) });
                            MethodInfo geneMethod = geneSecondType.GetMethod("GetCountryName");
                            MethodInfo geneSecondMethod = geneMethod.MakeGenericMethod(new Type[] { typeof(int) });
                            object geneObj = Activator.CreateInstance(geneSecondType);
                            geneSecondMethod.Invoke(geneObj, new object[] { "泛型类和泛型方法", 1 });
                        }
                        Console.ReadLine();
                    }

                    #endregion
                    #region 3.动态加载DLL的属性和字段
                    {
                        Assembly assembly = Assembly.Load("Assembly_1");
                        Type type = assembly.GetType("Assembly_1.People");
                        object obj = Activator.CreateInstance(type);
                        #region 属性
                        PropertyInfo[] propArr = type.GetProperties();
                        foreach (var prop in propArr)
                        {
                            if (prop.PropertyType == typeof(string))
                            {
                                prop.SetValue(obj, "设置string的值!");
                            }
                            if (prop.PropertyType == typeof(int))
                            {
                                prop.SetValue(obj, 1);
                            }
                            object objProp = prop.GetValue(obj);
                            Console.WriteLine(Convert.ToString(objProp));
                        }
                        #endregion
                        #region 字段
                        FieldInfo[] fieldArr = type.GetFields();
                        foreach (var fieldItem in fieldArr)
                        {
                            if (fieldItem.FieldType == typeof(string))
                            {
                                fieldItem.SetValue(obj, "字段名称");
                                object fieldValue = fieldItem.GetValue(obj);
                                Console.WriteLine(fieldValue.ToString());
                            }
                        }
                        #endregion
                    }
                    #endregion
                }
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
            #endregion
        }
    }
}

猜你喜欢

转载自blog.csdn.net/liuchang19950703/article/details/86720969