使用[NotNull]作为方法的参数

问题描述 投票:22回答:2

考虑ASP.NET MVC源代码中的this code

public static IApplicationBuilder UseMvc(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action<IRouteBuilder> configureRoutes) {...}

根据this的回答,带注释的参数不能为空。那为什么我可以将null传递给方法呢?也就是说,在下面的情况下,为什么编译器没有给我任何错误?

app.UseMvc(null);
c#
2个回答
32
投票

可能导致编译器生成错误的唯一属性是ObsoleteAttribute。这是因为该属性的行为被硬编码到编译器中。

NotNull属性这样的属性通常用于在编写代码时生成警告或错误的工具(如ReSharper)。请阅读有关此特定属性here的信息。

你也可以使用像PostSharp这样的工具来issue additional build-time errors


12
投票

如果您希望将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

© www.soinside.com 2019 - 2024. All rights reserved.