使用反射加载DLL调用方法时遇Page参数为空错误求助
空引用错误(parameter: page cannot be null)的排查与修复
核心问题分析
你的代码存在几个关键错误,直接导致了page参数为空的异常:
1. 程序集路径拼写错误
你写的路径是Eplan.EplApi.DataModelu.dll,末尾多了个字母u,正确的程序集名称应该是Eplan.EplApi.DataModel.dll。这个错误会导致加载的程序集无效,后续创建的page和instance对象大概率都是null。
2. Page实例创建方式错误
EPLAN的Page类不能直接通过CreateInstance无参构造实例化,它需要依托现有项目中的页面实例,或者通过EPLAN API的官方入口(比如Project对象)来获取,直接实例化的Page对象是未初始化的空对象。
3. 错误的属性获取逻辑
你试图获取Page类的Page属性,这本身就是逻辑错误——你已经拿到了Page对象,再去取它的Page属性只会返回空值,直接导致传入Create方法的参数为null。
4. Rectangle.Create方法调用方式错误
EPLAN的Rectangle.Create是静态方法,不需要创建Rectangle实例后调用,直接通过类类型调用即可,你创建的instance对象完全多余,甚至会因为实例未初始化导致调用失败。
修复后的代码示例
private void Test() { try { // 修正程序集路径 string assemblyPath = @"C:\Program Files\EPLAN\Platform\2022.0.3\Bin\Eplan.EplApi.DataModel.dll"; string rectangleTypeName = "Eplan.EplApi.DataModel.Graphics.Rectangle"; string pageTypeName = "Eplan.EplApi.DataModel.Page"; string createMethodName = "Create"; // 加载程序集并获取类型 Assembly assembly = Assembly.LoadFile(assemblyPath); Type rectangleType = assembly.GetType(rectangleTypeName); Type pageType = assembly.GetType(pageTypeName); // 获取有效Page实例(必须从EPLAN现有项目中获取) object page = GetActiveProjectPage(); if (page == null) { MessageBox.Show("未找到有效页面实例"); return; } // 获取静态Create方法 MethodInfo createMethod = rectangleType.GetMethod(createMethodName, new[] { pageType }); // 调用静态方法,第一个参数传null object rectangle = createMethod.Invoke(null, new[] { page }); } catch (Exception e) { MessageBox.Show(e.Message); if (e.InnerException != null) MessageBox.Show(e.InnerException.Message); } } // 从当前激活的EPLAN项目中获取第一个页面实例 private object GetActiveProjectPage() { // 加载EPLAN基础API程序集 Assembly baseAssembly = Assembly.LoadFile(@"C:\Program Files\EPLAN\Platform\2022.0.3\Bin\Eplan.EplApi.Base.dll"); Type projectManagerType = baseAssembly.GetType("Eplan.EplApi.Base.ProjectManager"); // 获取当前激活项目 PropertyInfo activeProjectProp = projectManagerType.GetProperty("ActiveProject"); object activeProject = activeProjectProp.GetValue(null); if (activeProject == null) return null; // 获取项目中的页面集合并取第一个页面 MethodInfo getPagesMethod = activeProject.GetType().GetMethod("GetPages"); IEnumerable pages = getPagesMethod.Invoke(activeProject, null) as IEnumerable; return pages?.Cast<object>().FirstOrDefault(); }
关键提示
- 所有EPLAN API对象都需要在EPLAN运行环境中初始化,不能脱离EPLAN进程直接创建实例。
- 优先使用EPLAN官方提供的API入口(比如ProjectManager、Selection等)获取对象,而非直接反射实例化。
- 反射调用时,必须明确方法是静态还是实例方法:静态方法调用
Invoke时,第一个参数必须传null。
内容的提问来源于stack exchange,提问作者Eugene Paul
相关产品推荐
相关产品推荐

