c#中编译器辅助的null契约

本文关键字:null 契约 编译器 | 更新日期: 2023-09-27 18:15:05

在Java中,可以用注释来注释方法,这些注释允许某些处理器推断null并在违反null契约时向您发出警告/编译器错误:

@NotNull    
public String returnSomething() {
    return null; // would give a warning as you violate the contract.
}
// at call site
if (returnSomething() != null) { // would give you a warning about unneccessary if
}
public int doSomethingElse(@NotNull String arg1, @Nullable String arg2) {
    return arg1.length() + arg2.length(); // would give you a warning about potential NPE when accessing arg2 without a check
}
// at call site
doSomethingElse(null, null); // would give you a warning about violating contract for arg1

c#中是否有类似的功能?

c#中编译器辅助的null契约

1)您可以使用Fody的 NullGuard。它在编译时工作(生成适当的IL代码):

public class Sample
{
    public void SomeMethod(string arg)
    {
        // throws ArgumentNullException if arg is null.
    }
    public void AnotherMethod([AllowNull] string arg)
    {
        // arg may be null here
    }
    [return: AllowNull]
    public string MethodAllowsNullReturnValue()
    {
        return null;
    }
}

编译时:

public class SampleOutput
{
    public void SomeMethod(string arg)
    {
        if (arg == null)
        {
            throw new ArgumentNullException("arg");
        }
    }
    public void AnotherMethod(string arg)
    {
    }
    public string MethodAllowsNullReturnValue()
    {
        return null;
    }
}
2)如果你使用ReSharper,你可以使用Contract Annotations