代码合同:如何为通用接口提供合同类? [英] Code Contracts: How do I supply a contract class for a generic interface?
问题描述
我想为这个通用接口指定一个契约,使用代码契约:
I'd like to specify a contract for this generic interface, using Code Contracts:
interface IRandomWriteAccessible<T>
{
T this[uint index] { set; }
uint Length { get; }
}
文档说在为接口指定契约时使用 ContractClass
属性.但是,编译器会抱怨这个:
The documentation says to use the ContractClass
attribute when specifying a contract for an interface. However, the compiler will complain about this:
[ContractClass(typeof(IRandomWriteAccessibleContract<T>))]
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <-- compiler error
interface IRandomWriteAccessible<T> { … }
[ContractClassFor(typeof(IRandomWriteAccessible<T>))]
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <-- compiler error
sealed class IRandomWriteAccessibleContract<T> : IRandomWriteAccessible<T> { … }
似乎类型参数不能与属性一起使用.
It seems that type parameters cannot be used with attributes.
我如何做为我的通用接口编写契约?或者代码契约无法做到这一点?
How do I write a contract for my generic interface? Or is this not possible with Code Contracts?
推荐答案
正如本问题中的其他评论所提到的,您应该从属性使用中删除泛型类型标识符,因为它无法在编译时解析:
As mentioned by other comments in this question, you should remove the generic type identifier from your attribute usage as it can not be resolved at compile time:
[ContractClass(typeof(IRandomWriteAccessibleContract<>))]
这篇关于代码合同:如何为通用接口提供合同类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!