为构造函数参数设置合同

时间:2015-06-02 23:43:21

标签: c# code-contracts contracts

假设我们在合同类

中有如下界面
[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)
         {
             ...
         } 
    }

使用throw new ArgumentNullException

替换构造函数中的Contract.Requires(obj != null).是否有意义

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

1 个答案:

答案 0 :(得分:1)

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

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

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