c#中的编译器辅助无效合同?

时间:2014-07-28 05:45:25

标签: c# code-contracts

在Java中,可以使用注释来注释方法,这些注释允许某些处理器推断无效,如果您违反了无效合同,则会给出警告/编译器错误:

@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#有类似的东西吗?

1 个答案:

答案 0 :(得分:1)

1)您可以使用 Fody&#39> <{strong> 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