Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 什么';静态只读的目的是什么;空的';在事件中_C#_Oop_Events - Fatal编程技术网

C# 什么';静态只读的目的是什么;空的';在事件中

C# 什么';静态只读的目的是什么;空的';在事件中,c#,oop,events,C#,Oop,Events,我是C#的新手,只是一个关于EventArgs类的问题。我们知道定义是: public class EventArgs { public static readonly EventArgs Empty; public EventArgs(); } 我猜其中一个用途就是当你不在乎传递自定义信息时 public event EventHandler<EventArgs> TestHappening; private void MyMethod() { TestHa

我是C#的新手,只是一个关于EventArgs类的问题。我们知道定义是:

public class EventArgs
{
   public static readonly EventArgs Empty;
   public EventArgs();
}
我猜其中一个用途就是当你不在乎传递自定义信息时

public event EventHandler<EventArgs> TestHappening;

private void MyMethod()
{
    TestHappening( this, EventArgs.Empty );
}

Empty只是定义一个没有数据的EventArgs实例。在C#中,有许多具有已定义属性的类来声明该类的状态、种类或值,以支持那些刚刚接近C#的人
string.Empty
int.MaxValue
等是这方面的示例

出于两个原因,最好使用
EventArgs.Empty

  • 检查参数是否为空很方便

    EventArgs newArgs = new EventArgs();
    EventArgs emptyArgs = EventArgs.Empty;
    Console.WriteLine(newArgs == EventArgs.Empty); // false
    Console.WriteLine(emptyArgs == EventArgs.Empty); // true
    
  • 没有额外的内存分配,因为您基本上使用相同的类实例
    在源代码中,its
    public static readonly EventArgs Empty=new EventArgs()这只是一个静态空成员,用于保存分配。我认为这只是更好的可读性。
    
    EventArgs newArgs = new EventArgs();
    EventArgs emptyArgs = EventArgs.Empty;
    Console.WriteLine(newArgs == EventArgs.Empty); // false
    Console.WriteLine(emptyArgs == EventArgs.Empty); // true