自定义代码合同exception消息

我有一个代码合同表示为 – 它validation要存储的实体不为空并且对持久性有效。 有用。 晶圆厂。

[ContractClassFor(typeof(IRepository))] internal abstract class ContractsForIRepository : IRepository where T : IEntity { private ContractsForIRepository() { } public T Persist(T entity) { Contract.Requires(entity != null, "Entity is null"); Contract.Requires(entity.IsValidForPersistence(), "Entity not valid for persistence"); return default(T); } } 

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

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

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

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

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

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

根据文件 :

2.10合同方法的超载

除了布尔条件之外,所有的合约方法都有重载,它们接受一个字符串:

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

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

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