C# Using Assembly to call a method within a DLL

折月煮酒 提交于 2019-11-30 07:38:41

The question and answer you reference is using reflection to call the method in the managed DLL. This isn't necessary if, as you say you want to do, you simply reference your DLL. Add the reference (via the Add Reference option in Visual Studio), and you can call your method directly like so:

ExampleDLL.Program p = new ExampleDLL.Program(); // get an instance of `Program`
p.myVoid(); // call the method `myVoid`

If you want to go the reflection route (as given by woohoo), you still need an instance of your Program class.

Assembly SampleAssembly = Assembly.LoadFrom(filename);
Type myType = SampleAssembly.GetTypes()[0];
MethodInfo Method = myType.GetMethod("myVoid");
object myInstance = Activator.CreateInstance(myType);
Method.Invoke(myInstance, null);

Now you have an instance of Program and can call myVoid.

//Assembly1.dll
using System;
using System.Reflection;

namespace TestAssembly
{
    public class Main
    {
        public void Run(string parameters)
        {
            // Do something... 
        }
        public void TestNoParameters()
        {
            // Do something... 
        }
    }
}

//Executing Assembly.exe
public class TestReflection
{
    public void Test(string methodName)
    {
        Assembly assembly = Assembly.LoadFile("...Assembly1.dll");
        Type type = assembly.GetType("TestAssembly.Main");
        if (type != null)
        {
            MethodInfo methodInfo = type.GetMethod(methodName);
            if (methodInfo != null)
            {
                object result = null;
                ParameterInfo[] parameters = methodInfo.GetParameters();
                object classInstance = Activator.CreateInstance(type, null);
                if (parameters.Length == 0)
                {
                    result = methodInfo.Invoke(classInstance, null);
                }
                else
                {
                    object[] parametersArray = new object[] { "Hello" };

                    result = methodInfo.Invoke(classInstance, parametersArray);
                }
            }
        }
    }
}

Just add this line of code after you obtain reference to your method.

            Method.Invoke(classInstance, new object[] {});

Hope this help.

MethodInfo has a method called Invoke. So simply call Method.Invoke() with an object you created by for example calling System.Activator.CreateInstance()

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