Skip to main content
 首页 » 编程设计

c#之在继承链中重复代码契约要求

2024年02月20日13飞鱼

假设您有一个现有的大型项目,并且您想要在其中集成代码契约(Contract)。现有代码使用 if-null-then-throw 逻辑。对于给定的条件,文档建议将汇编模式设置为自定义参数验证。

我有以下类(class):

class A 
{ 
    protected virtual void Foo(int a, int b) 
    { 
        if (a == null) 
            throw new ArgumentNullException(a); 
        if (b == null) 
            throw new ArgumentNullException(b); 
        Contract.EndContractBlock(); 
    } 
} 
class B : A 
{ 
    protected override void Foo (int a, int b) 
    { 
        // some stuff 
        base.Foo(a, b); 
    } 
} 

当我编译时,我收到以下警告:

warning CC1055: Method 'B.Foo(int, int)' should contain custom argument validation for 'Requires(a != null)' as it overrides 'A.Foo(int,int)' which suggests it does. If you don't want to use custom argument validation in this assembly, change the assembly mode to 'Standard Contract Requires'.

我不想在每个被覆盖的方法上重复前提条件!有解决办法吗?

请您参考如下方法:

如果您使用 Contract.Requires() 而不是 Contract.EndContractBlock(),它工作正常。

下面引用的手册中有一节建议将 [SuppressMessage] 属性添加到方法重写。

来自Code Contracts user manual p.22 第 5.2.3 节。

Delegating Checks to Other Methods

Suppose you have a code pattern similar to the following code:

public class Base { 
    public virtual void Compute(string data) { 
    if (data == null) throw new ArgumentNullException(...); 
        Contract.EndContractBlock(); 
        ... 
    } 
} 
 
public class Derived : Base { 
    public override void Compute(string data) { 
        base.Compute(data); 
        ... 
    } 
} 

Then the tools will issue warning CC1055 with a message of the form:

Method ’Derived.Compute’ should contain custom argument validation for ' Requires (ArgumentNullException)(data ! = null)' as it overrides 'Base.Compute' which suggests it does.

在这种情况下,警告没有帮助,因为实现 Derived.Compute 的将参数验证委托(delegate)给另一个 方法(在本例中为基本方法)。为了避免这个警告 在不重复验证的情况下,可以添加一个 方法的 SuppressMessage 属性:

public class Derived : Base { 
    [SuppressMessage("Microsoft.Contracts", "CC1055", Justification = "Validation performed in base method")] 
    public override void Compute(string data) { 
        base.Compute(data); 
        ... 
    } 
}