尝试使用在控制台应用程序运行时导入的 DLL 显示 Windows 表单

Trying to show a Windows Form using a DLL that is imported at the runtime in a console application

我正在做一些研究项目,这个迷你项目是其中的一部分。这个小项目的objective是在运行时导入DLL,加载存储在那个DLL中的GUI。我试图从 DLL 的函数中触发 Windows Form 的 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 Class 库代码

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;
        }
    }
}

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

'TestLib.Form1' does not contain a definition for 'test'

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

问题是 Activator.CreateInstance 没有 return ExpandObject(动态)。 你应该 运行 test() 通过反思,像这样:

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