【问题标题】:Jetbrains ContractAnnotations interface or implementationJetbrains ContractAnnotations 接口或实现
【发布时间】:2023-03-14 04:59:01
【问题描述】:

在使用 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 的代码分析也可以与继承的合同一起使用。


有人能解释一下是否需要将此注释放在接口和实现中吗?

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

【问题讨论】:

  • blog.jetbrains.com/dotnet/2012/08/15/… 谈到了添加属性的影响(即它显示了 Resharper 将如何提供额外的反馈)。鉴于此,我的建议是先尝试将其添加到界面中。它会给你反馈吗?如果没有,请尝试将其添加到课程中。如果没有,请尝试将其添加到两者中。 实际上,您应该将其添加到两者中 - 特别是在涉及 DI/IOC 的代码库中。

标签: c# annotations resharper jetbrains-ide


【解决方案1】:

我做了更详细的测试,发现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.
    }
}

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    相关资源
    最近更新 更多