如何从外部程序集中调用方法

时间:2020-08-02 11:59:51

标签: c# .net .net-core

我有示例c#项目:

namespace SampleExe
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

我有示例C#dll:

namespace SampleDll
{
    public class Program
    {
        public static void TestMethod(string samplestr)
        {
            Console.WriteLine("TestMethod Void Runned! Your string is: "+samplestr);
        }
    }
}

如何从已编译的SampleDll.DLL中调用TestMethod()(我想加载外部dll)

3 个答案:

答案 0 :(得分:0)

您有多种选择。您可以创建一个dll并将该dll添加为对该项目的引用。您也可以将项目添加为参考。您还可以创建dll的NuGet程序包并使用它。

然后只需致电SampleDll.Program.TestMethod

答案 1 :(得分:0)

为此,您需要使用反射。

            var assembly = Assembly.Load(File.ReadAllBytes("SampleDLL.dll"));

            foreach(Type type in assembly.GetExportedTypes())
            {
                var c = Activator.CreateInstance(type);
                type.InvokeMember("TestMethod", BindingFlags.InvokeMethod, null, c, new object[] { @"Hi!" });
            }

答案 2 :(得分:0)

这是一个使用Reflection在运行时加载库并执行静态方法的工作示例。请注意,它有很多假设:您必须提前知道库名称,类名称,方法名称及其所有参数。直接引用库通常要容易得多。

成功使用反射的一种好方法是与继承/接口一起使用。库A包含基类或接口,库B包含派生类。库A可以使用反射来加载库B,然后在库B 中找到从基类或接口派生的所有类类型(使用Type.IsAssignableFrom)。这样,库A将具有强类型化的属性和方法来从基础使用,而不必知道库B中的类,方法和属性的字符串名称。 >

执行反射的主要EXE代码:

using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace SomeNamespace
{
    public class Program
    {
        static void Main()
        {
            string pathToSampleDLL = "<if you know the path ahead of time, use it>";

            // if SampleDLL.dll is in same directory as this EXE (a common occurrence):
            string workingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            pathToSampleDLL = Path.Combine(workingDirectory, "SampleDLL.dll");

            // load the DLL at runtime
            Assembly sampleDLL = Assembly.LoadFrom(pathToSampleDLL);

            // since you know the type name, you can use LINQ to return your type:
            Type sampleType = sampleDLL.GetTypes().FirstOrDefault(t => t.Name == "Program");

            // you are looking for a static method on this type, and you know its name, so use GetMethods:
            MethodInfo staticMethod = sampleType.GetMethod("TestMethod", BindingFlags.Public | BindingFlags.Static);

            // invoke the method.  Since you know its arguments and return value ahead of time, just hard code it:
            // you can use null for the object since this is a static method.  It takes only one argument, a sample string
            staticMethod.Invoke(null, new object[] { "sampleStr" });
        }
    }
}

示例库的代码(编译为“ SampleDLL.dll”):

using System;

namespace SampleDll
{
    public class Program
    {
        public static void TestMethod(string sampleStr)
        {
            Console.WriteLine("TestMethod Void Runned! Your string is: " + sampleStr);
        }
    }
}
相关问题