c# - 为什么未使用的事件参数需要赋值?

标签 c# events delegates event-handling arguments

根据 C# Reference

"The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables'

我很惊讶地发现
注释以下应用程序代码中的 e=null 行(摘自文章 "Difference Between Events And Delegates in C#" )会导致编译错误:

Use of unassigned local variable 'e'

虽然没有注释,但已编译并运行。

我没有得到:

  • 变量 e 在哪里使用?
  • 是否可以在不将变量分配给 null 的情况下强制应用程序运行?

f

using System;   
class Program   
{   
  static void Main(string[] args)   
  {   
    DelegatesAndEvents obj = new DelegatesAndEvents();   
    obj.Execute();  
  }  
}  
public class DelegatesAndEvents  
{
  public event EventHandler MyEvent;
  internal void Execute()
  {
    EventArgs e;
//Commenting the next line results in compilation error
//Error 1   Use of unassigned local variable 'e'
    e = null;
    int sender = 15;
    MyEvent += MyMethod;
    MyEvent += MyMethod2;
    MyEvent(sender, e);
  }
  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
  }
  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}

更新(或对所有答案的评论):
所以,我从来不知道,有一种 null - 一个被分配,另一个没有被分配......有趣......

它们应该有不同的类型,用于检查:
如果 typeof(unassigned-null) 则执行此操作;
如果是 typeof(assigned_null) 那么就这样做;

最佳答案

局部变量没有用它们的默认值初始化,而字段是。

关于c# - 为什么未使用的事件参数需要赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876089/

相关文章:

c# - 如何在 Office 功能区开发的编辑框中隐藏密码文本

angular - 我可以使用多个@hoSTListener 或基于浏览器的事件吗?

javascript - Nodejs异步事件导致顺序错误

c# - 防止在多对多表上按约定创建索引

c# - PowerShell 未在 SqlConnectionStringBuilder 上设置属性(适用于 C#)

c# - <>在C#中的意义

iPhone:应用程序委托(delegate)中的 NSTimer 无效导致应用程序崩溃

asp.net - 使用事件处理错误,检查是否发生错误并做出相应 react

c# - CallBack on garbagecollected Delegate

c# - 使用 ExpressionTree 将委托(delegate) (Action<TObject, TValue>) 检索到索引器的 Setter