根据C# Reference
“ null关键字是表示空引用的文字,一个
没有引用任何对象。 null是的默认值
引用类型的变量”
我很惊讶地发现
在以下应用程序代码中(从文章"Difference Between Events And Delegates in C#"中摘录)注释e=null
行会导致编译错误:
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();
}
}
更新(或对所有答案的评论):
所以,我从来不知道,有一些空值-一个被分配,另一个未被分配...好笑...
它们可能应该具有不同的类型,以进行检查:
如果typeof(unssigned-null)则执行此操作;
如果typeof(assigned_null)则执行此操作;
最佳答案
局部变量不使用其默认值初始化,而字段初始化。
关于c# - 为什么未使用的事件参数需要分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876089/