C#如何在程序集类型中使用读取方法

问题描述

我正在编写一个数据采集应用程序,它使用硬件驱动程序的包装类。我的目标是让外部用户能够为他们的硬件编写自己的包装器。似乎程序集是存储这些驱动程序包装器的方式,由应用程序加载。所以我从一个基于 Microsoft 示例的非常简单的测试代码开始: Loading DLLs at runtime in C# 它在写入程序集方法时起作用。我添加了一个 read 方法,但它不起作用。见代码:

namespace DLL
{
    using System;

    public class Class1
    {
        public void Output(string s)
        {
            Console.WriteLine(s);
        }
        public string DriverName()      // My added method
        {
            return "Test";
        }
    }
}

这里是主要的:

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    // See: https://stackoverflow.com/questions/18362368/loading-dlls-at-runtime-in-c-sharp
    
    public class Program
    {
        public static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"...\Documents\VS\Tests\DLL Test\DLL\bin\Debug\netstandard2.0\DLL.dll");
            foreach (Type type in DLL.GetExportedTypes())
            
                dynamic c = Activator.CreateInstance(type);
                c.Output("Hello");                    // Works
                Console.WriteLine(c.DriverName());    // Doesn't work
            }
            Console.ReadLine();
        }
    }
}

它给出了一个编译时错误:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''DLL.Class1' does not contain a definition for 'DriverName''

为什么这只能以一种方式起作用而另一种不起作用?有没有简单的解决办法?

解决方法

试着加括号

namespace ConsoleApplication1
{
    using System;
    using System.Reflection;

    // See: https://stackoverflow.com/questions/18362368/loading-dlls-at-runtime-in-c-sharp
    
    public class Program
    {
        public static void Main(string[] args)
        {
            var DLL = Assembly.LoadFile(@"...\Documents\VS\Tests\DLL Test\DLL\bin\Debug\netstandard2.0\DLL.dll");
            foreach (Type type in DLL.GetExportedTypes())
            {
                dynamic c = Activator.CreateInstance(type);
                c.Output("Hello");                    // Works
                Console.WriteLine(c.DriverName());    // Doesn't work
            }
            Console.ReadLine();
        }
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...