使用英语阅读

通过


EventArgs 类

定义

表示包含事件数据的类的基类,并提供用于不包含事件数据的事件的值。

C#
public class EventArgs
C#
[System.Serializable]
public class EventArgs
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class EventArgs
继承
EventArgs
派生
属性

示例

以下示例演示派生自 EventArgs 类的名为 ThresholdReachedEventArgs 的自定义事件数据类。 事件数据类的实例将传递给事件的事件处理程序 ThresholdReached

C#
using System;

namespace ConsoleApplication3
{
    public class Program3
    {
        public static void Main()
        {
            Counter c = new(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");
                c.Add(1);
            }
        }

        static void c_ThresholdReached(object? sender, ThresholdReachedEventArgs e)
        {
            Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold,  e.TimeReached);
            Environment.Exit(0);
        }
    }

    class Counter
    {
        private readonly int _threshold;
        private int _total;

        public Counter(int passedThreshold)
        {
            _threshold = passedThreshold;
        }

        public void Add(int x)
        {
            _total += x;
            if (_total >= _threshold)
            {
                ThresholdReachedEventArgs args = new()
                {
                    Threshold = _threshold,
                    TimeReached = DateTime.Now
                };
                OnThresholdReached(args);
            }
        }

        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
        {
            ThresholdReached?.Invoke(this, e);
        }

        public event EventHandler<ThresholdReachedEventArgs>? ThresholdReached;
    }

    public class ThresholdReachedEventArgs : EventArgs
    {
        public int Threshold { get; set; }
        public DateTime TimeReached { get; set; }
    }
}

注解

此类用作表示事件数据的所有类的基类。 例如, System.AssemblyLoadEventArgs 类派生自 EventArgs ,用于保存程序集加载事件的数据。 若要创建自定义事件数据类,请创建派生自 类 EventArgs 的类,并提供用于存储必要数据的属性。 自定义事件数据类的名称应以 结尾 EventArgs

若要传递不包含任何数据的对象,请使用 Empty 字段。

有关事件的详细信息,请参阅 处理和引发事件 一文。

构造函数

EventArgs()

初始化 EventArgs 类的新实例。

字段

Empty

提供要用于没有事件数据的事件的值。

方法

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅