【问题标题】:Putting Contracts for Constructor Arguments为构造函数参数设置合约
【发布时间】:2015-06-02 23:43:20
【问题描述】:

假设我们与合约类有如下接口

[ContractClassFor(typeof(Custom))]
public abstract class CustomContract : Custom
{
    public string GetPerson(int i)
    {
        Contract.Requires(i > 0);
        Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
        return default(string);
    }
    public string Name { get; set; }
}

[ContractClass(typeof(CustomContract))]
    public interface Custom
    {
        string GetPerson(int i);
        string Name { get; set; }
    }

实现就像

    public class CustomProcessor: Custom
    {
         public CustomProcessor(ISomeinterface obj, string logname)
         {
              if(null == obj) throw new ArgumentNullException(...);
               ...
         }
         public GetPerson(int I)
         {
             ...
         } 
    }

Contract.Requires(obj != null).替换构造函数中的throw new ArgumentNullException有意义吗

合同应该由接口定义,因为构造函数是实现的一部分,而不是接口,所以我倾向于当前的方法。 这是一个好习惯吗?

【问题讨论】:

    标签: c# code-contracts contracts


    【解决方案1】:

    为了充分利用代码合同,是的,将 ArgumentNullException 抛出替换为 Contract.Requires 是有意义的。

    考虑到您使用的是接口和合同类,这完全没问题。除了在构造函数本身之外,没有其他地方可以验证构造函数参数。

    如果您使用ArgumentNullException 方法,那么您将错过代码合约的静态检查和其他好处。

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2018-09-16
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多