如何从dll文件订阅事件并获取由dll生成的列表

本文关键字:dll 获取 列表 事件 文件 | 更新日期: 2023-09-27 18:17:32

所以我有一个生成人和关于他们的数据的dll文件。每次发生变化时,dll都会引发一个事件。我需要订阅事件,然后处理数据。

我有以下关于dll的信息

namespace PeopleGenerator 
{ 
    public class RawPeopleDataEventArgs : EventArgs 
    {
        public RawPeopleDataEventArgs(List<string> peopleData) 
        {
            PeopleData = peopleData; 
        }
        public List<string> PeopleData { get; } 
    }
    public interface IPeopleGenerator 
    {
        event EventHandler<RawPeopleDataEventArgs>  PeopleDataReady; 
    }
} 

我也得到了一个工厂的信息,我可以用它来获得一个IPeopleGenerator对象

namespace PeopleGenerator 
{ 
    public class PeopleGeneratorFactory 
    {
        public static IPeopleGenerator CreatePeopleDataReceiver() 
    }
}

现在我尝试创建一个订阅类

namespace Test
{
    class EventSubscriber
    {       
        public EventSubscriber(object o, RawPeopleDataEventArgs args)
        {
            List<string> listofpeople = args.PeopleData;
            printList(listofpeople);
        }
        void printList(List<string> print)
        {
            print.ForEach(Console.WriteLine);
            // More data processing to happen here
        }
    }
}

我的问题是我不知道如何开始从dll生成数据。使用工厂类。我的想法是这样的

static void Main(string[] args)
{
    //generate a new object
    EventSubscriber sub = new EventSubscriber(????);
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
}

如何从dll文件订阅事件并获取由dll生成的列表

您订阅的是方法,而不是类,可以按照以下方式修改订阅者:

 namespace Test
    {
        class EventSubscriber
        {       
            public HandlePeople(object o, RawPeopleDataEventArgs args)
            {
                List<string> listofpeople = args.PeopleData;
                printList(listofpeople);
            }
            void printList(List<string> print)
            {
                print.ForEach(Console.WriteLine);
                // More data processing to happen here
            }
        }
    }  

并使用订阅者实例(及其方法)来处理事件:

static void Main(string[] args)
    {
        var recvr = PeopleGenerator.PeopleGeneratorFactory.CreatePeopleDataReceiver();
        var subscriber = new EventSubscriber();
        recvr.PeopleDataReady += new subscriber.Handle;
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }