一、主项目不添加引用
(主项目不添加引用,而是通过路径获取指定dll)
1.打印类的属性名称
namespace ReflectionDemo
{class Program{static void Main(string[] args){// 指定【编译输出】的项目类库dll(启动项目编译输出目录下的dll)string assemblyPath = @"F:\Personal\demo\bin\Debug\net5.0\BuildDatabaseTable.dll";// 指定【类名.命名空间】string className = "BuildDatabaseTable.DataSchoolDto"; PrintFieldNames(assemblyPath, className);}public static void PrintFieldNames(string assemblyPath, string className){try{// 加载指定路径的程序集Assembly assembly = Assembly.LoadFrom(assemblyPath);// 打印所有类库下的所有类var classList = assembly.ExportedTypes.ToList();var classNameList = classList.Select(x => x.FullName).ToList();Console.WriteLine(string.Join("\n", classList));// 获取指定类的类型Type type = assembly.GetType(className);if (type != null){// 获取类的所有属性var fields = type.GetProperties();// 打印每个属性的名称Console.WriteLine($"{className}的属性有:");foreach (var field in fields){Console.WriteLine(field.Name);}}else{Console.WriteLine($"未找到这个类:{className} ");}}catch (Exception ex){Console.WriteLine($"发生错误: {ex.Message}");}}}}
2.调用相应方法
namespace ReflectionDemo
{class Program{static void Main(string[] args){// 指定【编译输出】的项目类库dll(启动项目编译输出目录下的dll)string assemblyPath = @"F:\Personal\demo\bin\Debug\net5.0\BuildDatabaseTable.dll";// 指定【类名.命名空间】string className = "BuildDatabaseTable.DataSchoolDto"; // 指定【方法名称】string methodName = "ProcessInt";// 调用方法CallMethod(assemblyPath, className, methodName, 5);}public static void CallMethod(string assemblyPath, string className, string methodName, params object[] parameters){try{// 加载指定路径的程序集Assembly assembly = Assembly.LoadFrom(assemblyPath);// 获取类的类型Type type = assembly.GetType(className);if (type == null){Console.WriteLine($"无法找到类:{className}");return;}// 判断类是否为静态类bool isStatic = type.IsAbstract && type.IsSealed;// 获取方法信息MethodInfo method = type.GetMethod(methodName);if (method == null){Console.WriteLine($"未找到方法 {methodName}");return;}// 如果是静态方法,直接调用if (isStatic){object result = method.Invoke(null, parameters);Console.WriteLine($"静态方法调用结果:{result}");}else{// 非静态方法,先创建实例object instance = Activator.CreateInstance(type);object result = method.Invoke(instance, parameters);Console.WriteLine($"非静态方法调用结果:{result}");}}catch (Exception ex){Console.WriteLine($"发生错误: {ex.Message}");}}}}
【注意】:如果是同一个解决方案下的类库相互加载、引用,不需要写完整路径,可直接写dll
跨解决方案:
string assemblyPath = @"F:\Personal\demo\bin\Debug\net5.0\BuildDatabaseTable.dll";
同一解决方案,可以写为:
string assemblyPath = @"BuildDatabaseTable.dll";
二、主项目添加引用
1.添加项目引用
2.使用引用
static void Main(string[] args)
{try{//调用方法(dll名称.类名)var res = BuildDatabaseTable.Program.ProcessInt(3);Console.WriteLine(res);//获取实例(dll名称.类名)var entity = new BuildDatabaseTable.DistrictSandData();entity.Id = 1;}catch (Exception ex){Console.WriteLine($"发生错误: {ex.Message}");}
}