在using子句的上下文中调用null引用的方法是可以的吗?

Jak*_*les 8 c# null nullreferenceexception

我正在查看Stack Overflow团队在Google Code上设计的mvc-mini-profiler,并且在入门页面上有一件事让我感到特别奇怪:

var profiler = MiniProfiler.Current; // it's ok if this is null

using (profiler.Step("Set page title"))
{
    ViewBag.Title = "Home Page";
}
Run Code Online (Sandbox Code Playgroud)

如果探查器为空,它怎么能"ok"?在我看来,调用Step会抛出一个NullReferenceException.在我编程C#的所有这些年里,我从来都不知道在任何上下文中调用null引用上的方法都是"ok".这是使用子句的特殊情况吗?

我能理解这是好的(不知道它是,但显然它是?):

using (null)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是在null引用上调用方法似乎应该抛出异常,无论它是否在using子句中.有人可以解释如何在幕后翻译这样的结构,所以我可以理解为什么这样做是可以的?

Jon*_*eet 12

如果为null 则绝对不行,除非实际上是一个扩展方法.该语句不影响.profiler profiler.Stepusing

事实证明,扩展方法部分正是正在发生的事情.MiniProfiler.cs的第584-587行:

public static IDisposable Step(this MiniProfiler profiler, string name,
                               ProfileLevel level = ProfileLevel.Info)
{
    return profiler == null ? null : profiler.StepImpl(name, level);
}
Run Code Online (Sandbox Code Playgroud)

这就是profiler.Stepprofilernull为空时被调用的方式.它不是实例方法 - 调用转换为:

MiniProfilerExtensions.Step(profiler, ...);
Run Code Online (Sandbox Code Playgroud)

这是罚款profiler.Step,以返回空值,根据您的问题的第二部分.

  • Facepalming现在在Mehrdad询问Step是否是扩展方法之后我意识到它是.谢谢你们俩.:) (2认同)

Meh*_*dad 5

Step必须是一个扩展方法,我在评论中的猜测.

否则你的编译器会被肢解,或者你会产生幻觉.:-)