【问题标题】:Trying to show a Windows Form using a DLL that is imported at the runtime in a console application尝试使用在控制台应用程序运行时导入的 DLL 显示 Windows 窗体
【发布时间】:2015-05-12 03:16:05
【问题描述】:

我正在做一些研究项目,这个迷你项目是其中的一部分。这个迷你项目的目标是在运行时导入 DLL 并加载存储在该 DLL 中的 GUI。我正在尝试从 DLL 的函数中触发 Windows 窗体的 Show() 函数。代码如下所示: 控制台应用程序代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace DLLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string DLLPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\TestLib.dll";
            var DLL = Assembly.LoadFile(DLLPath);

            foreach (Type type in DLL.GetExportedTypes())
            {
                dynamic c = Activator.CreateInstance(type);
                c.test();
            }

            Console.ReadLine();
        }
    }
}

DLL 类库代码

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

namespace TestLib
{
    public class Test
    {
        public int test()
        {
            Form1 form = new Form1();
            form.Show();
            return 0;
        }
    }
}

当我返回一些值并在控制台应用程序上显示时,函数test() 工作正常。但是,当我尝试显示表单时,它向我显示了这个异常:

“TestLib.Form1”不包含“test”的定义

请告诉我如何解决这个问题?

【问题讨论】:

    标签: c# .net winforms dll console-application


    【解决方案1】:

    问题是Activator.CreateInstance 不返回ExpandObject(动态)。 您应该通过反射运行 test(),如下所示:

        foreach (Type type in DLL.GetExportedTypes())
        {
            dynamic c = Activator.CreateInstance(type);
            MethodInfo methodInfo = type.GetMethod("test");
             methodInfo.Invoke(c , null);
        }
    

    【讨论】:

    • 非常感谢。我的表格终于出现了。但是现在的问题是表格出现后冻结。你能帮我解决这个问题吗?
    • 你应该为它创建一个新主题。
    猜你喜欢
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2016-01-19
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多