考虑ASP.NET MVC源代码中的this code:
public static IApplicationBuilder UseMvc(
[NotNull] this IApplicationBuilder app,
[NotNull] Action<IRouteBuilder> configureRoutes) {...}
根据this的回答,带注释的参数不能为空。那为什么我可以将null传递给方法呢?也就是说,在下面的情况下,为什么编译器没有给我任何错误?
app.UseMvc(null);
可能导致编译器生成错误的唯一属性是ObsoleteAttribute
。这是因为该属性的行为被硬编码到编译器中。
像NotNull
属性这样的属性通常用于在编写代码时生成警告或错误的工具(如ReSharper)。请阅读有关此特定属性here的信息。
你也可以使用像PostSharp这样的工具来issue additional build-time errors。
如果您希望将Null检查移动到方面,而不需要手动完成。明确的解决方案是使用Fody开源构建编织器。具体来说,你想利用NullGuard Fody
PM>安装包NullGuard.Fody
应该是设置为使用带有零防护的Fody所需的一切。文档显示了如果您愿意,您可以如何进行细粒度控制。
2019年更新
C#8和.NET Core 3.0永久消除了空引用异常。
Tutorial: Migrate existing code with nullable reference types
Tutorial: Express your design intent more clearly with nullable and non-nullable reference types