自定义代码合同异常消息

时间:2012-09-27 09:31:47

标签: c# exception code-contracts

我有一个代码合约表示为 - 它验证要存储的实体不为空并且对持久性有效。有用。 FAB。

[ContractClassFor(typeof(IRepository<,>))]
internal abstract class ContractsForIRepository<T, TId> : IRepository<T, TId> where T : IEntity
{
    private ContractsForIRepository()
    {

    } 

    public T Persist(T entity)
    {
        Contract.Requires<InvalidEntityException>(entity != null, "Entity is null");
        Contract.Requires<InvalidEntityException>(entity.IsValidForPersistence(), "Entity not valid for persistence");
        return default(T);
    }

}

但是,我希望异常更有用 - 因为任何接收消息的人都想知道哪个实体无效且看起来像什么。所有实体都覆盖ToString(),所以我想在错误消息中包含它:

Contract.Requires<InvalidEntityException>(entity.IsValidForPersistence(), "Entity not valid for persistence " + entity.ToString());

我已经将ToString包含为显式 - 如果我省略它会隐式调用它,但我认为它使我的问题更加清晰。

问题是,代码合同不允许这样做,我收到以下消息。

  

合同调用的用户消息只能是字符串文字,或静态字段或至少在内部可见的静态属性。

有没有办法在异常消息中包含特定数据?

1 个答案:

答案 0 :(得分:2)

根据documentation

  

2.10合约方法超载

     

所有合约方法都有带字符串的重载   除了布尔条件:

     

Contract.Requires(x != null, "If x is null, then the missiles are red!");

     

合同到时,将显示用户提供的字符串   在运行时违反。 目前,它必须是编译时常量

所以,你所要求的是不可能的。

相关问题