【发布时间】:2013-01-30 07:54:22
【问题描述】:
"null 关键字是一个字面量,表示一个空引用,一个 那不涉及任何对象。 null 是的默认值 引用类型变量'
我很惊讶地发现
在以下应用代码中注释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();
}
}
更新(或对所有答案的评论):
所以,我从来不知道,有一种空值 - 一个已分配,另一个未分配......有趣......
他们可能应该有不同的类型,用于检查:
如果 typeof(unassigned-null) 则执行此操作;
如果 typeof(assigned_null) 则执行此操作;
【问题讨论】:
-
查看 Eric 和 Mark 对非常相似的问题的回答 stackoverflow.com/questions/1423437/… 和 stackoverflow.com/questions/8931226/…
-
The reason this is illegal in C# is because using an unassigned local has high likelihood of being a bug- Eric Lippert(来自上面的链接) -
e用于MyEvent(sender, e)行。编译器不会进行全面分析以确定所有订阅者都忽略了e参数。 (谁知道呢。既然是公开活动,可能其他人订阅了MyEvent,而其他人使用了e。) -
不,没有两种空值。您只是在处理 C# 的明确分配规则 - 即您可能 不从尚未分配值的局部变量中读取。这超出了 CLR 的要求(确保任何引用变量在第一次赋值之前都是
null)。因为,正如@asawyer 在他们的评论中指出的那样,忘记赋值是错误的常见来源。 -
@Damien_The_Unbeliever,那是个笑话
标签: c# events delegates event-handling arguments