根据 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/