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

烂漫一生 提交于 2019-12-13 09:44:41

问题


I am working on some research project and this mini project is a part of it. The objective of this mini project is to import the DLL at runtime and load the GUI stored in that DLL. I am trying to fire Show() function of Windows Form from a function of the DLL. Here's how the code looks like: Console Application Code

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 Library Code

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

The function test() is working fine when I just return some value and show on the console application. But, when I try to show the form, its showing me this exception:

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

Please tell me how can I solve this?


回答1:


The problem is that Activator.CreateInstance does not return ExpandObject (dynamic). You should run test() by reflection, like this :

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


来源:https://stackoverflow.com/questions/28967874/trying-to-show-a-windows-form-using-a-dll-that-is-imported-at-the-runtime-in-a-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!