Trying to show a Windows Form using a DLL that is

2019-09-22 00:49发布

问题:

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