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

时间:2016-11-12 16:39:18

标签: c# events dll

所以我有一个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();
}

1 个答案:

答案 0 :(得分:0)

您订阅方法,而不是类,修改您的订阅者如下:

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