从发件人处获取发布商类字段

时间:2018-01-22 20:51:15

标签: c# events sender

我想得到我的字段>>>来自发件人的 NumberOfElementsInMyList ,我该怎么办?我在这里找不到这样的问题(我看到的是关于Windows窗体),所以......

class Program
{
    static void Main(string[] args)
    {
        Publisher PublisherObject = new Publisher();
        PublisherObject.NumberAdded += PublisherObject_NumberAdded;

        PublisherObject.AddNumber(int.Parse(Console.ReadLine());
    }

    static void PublisherObject_NumberAdded(object sender, EventArgs e)
    {
        //I want to write on the console  "NumberOfElementsInMylist"

        //I tried: 

        //sender.NumberOfElementsInMylist -- not works
        //Publisher obj=(publisher)sender   and then sender.NumberOfElementsInMylist
        //not works
        Console.WriteLine("number of elements in list is ---> "+ ???? );
    }
}

class Publisher
{
    public event EventHandler NumberAdded;

    public int NumberOfElementsInMyList;

    List<int> MyList=new List<int>();

    public void AddNumber(int NumberToAdd)
    {
        MyList.Add(NumberToAdd);

        NumberOfElementsInMyList = MyList.Count;

        NumberAdded(this, new EventArgs());
    }
}

2 个答案:

答案 0 :(得分:0)

要真正回答您的问题,您无法访问NumberOfElementsInMyList字段的原因是因为在您创建EventArgs时,您的Publisher实例正在被转换为{ {1}}(您可以执行此操作,因为所有类都从object继承。)因此,要查看object的属性(或字段),您必须将Publisher强制转换为sender

Publisher

缺点是假设var numberOfElements = ((Publisher)sender).NumberOfElementsInMyList; 可能不是sender。由于Publishersender,因此技术上可以是任何内容。

您还可以创建自己的事件处理程序委托和事件参数,而不是使用样板object委托。

EventHandler

public delegate void NumberAdded(Publisher source, NumberAddedEventArgs eventArgs); public class NumberAddedEventArgs : EventArgs { public NumberAddedEventArgs(int numberAdded, numberOfItemsInList) { NumberAdded = numberAdded; NumberOfItemsInList = numberOfItemsInList; } public int NumberAdded { get; private set; } public int NumberOfItemsInList { get; private set; } } public class Publisher { public event EventHandler NumberAddedEvent; public int NumberOfElementsInMyList; List<int> MyList = new List<int>(); public void AddNumber(int NumberToAdd) { MyList.Add(NumberToAdd); NumberOfElementsInMyList = MyList.Count; NumberAddedEvent?.Invoke(this, new NumberAddedEventArgs(NumberToAdd, NumberOfElementsInMyList)); } } var numberOfElementsInList = args.NumberOfItemsInList; // much better! 是一个奇怪的惯例。在任何其他场景中,我们将创建强类型方法和委托。但在这种情况下,有一种趋势是使用不强类型的东西,因为它是一种惯例。

答案 1 :(得分:0)

您可以简单地投射sender,不是吗?

var publisher = (Publisher)sender;
Console.WriteLine(publisher.NumberOfElementsInMyList);

或者更安全:

Console.WriteLine(
    (sender as Publisher)?.NumberOfElementsInMyList?.ToString() ?? "sender is not a publisher!");