Jetbrains ContractAnnotations 接口或实现

Jetbrains ContractAnnotations interface or implementation

在使用 Jetbrains 时 ContractAnnotation 我想知道是否将它们放在接口方法、实现方法或两者上。 例如(简单示例)

public interface MyInterface
{
    [ContractAnnotation("=> notnull")]
    MyClass MakeInstance();
}

public class MyFactory : MyInterface
{
    [ContractAnnotation("=> notnull")] // Is this needed here, too?
    MyClass MakeInstance()
    {
        return new MyClass();
    }
}

我觉得把ContractAnnotation同时放在接口和实现上有点多余,但是documentation并没有提到放在哪里。

我发现 ContractAnnotations 可以继承,但我不知道这是否意味着 ReSharper 的代码分析也可以处理继承的契约。


有人可以阐明是否需要在接口和实现中都放置此注释吗?

如果两个地方都不需要它,哪里最有意义?

我做了更详细的测试,发现 ContractAnnotations 实际上是继承的,代码分析实际上考虑了继承的契约。


public class Class
{
    public bool Get() => true;
}

public interface IFactory
{
    [ContractAnnotation("=> notnull")]
    Class GetInstance();
}

public class Factory : IFactory
{
    // No redundant ContractAnnotation needed here.
    public Class GetInstance()
    {
        return new Class();
    }
}

public class DemoHost
{
    public void Run()
    {
        IFactory ifactory = new Factory();
        ifactory.GetInstance().Get(); // No null warning here.

        Factory factory = new Factory();
        factory.GetInstance().Get(); // No null warning here as well: obviously the annotation must have been inherited.
    }
}