代码契约:如何为通用接口提供契约类?
我想使用代码契约为这个通用接口指定一个契约:
interface IRandomWriteAccessible<T>
{
T this[uint index] { set; }
uint Length { get; }
}
文档说在为接口指定契约时使用 ContractClass
属性。然而,编译器会抱怨这一点:
[ContractClass(typeof(IRandomWriteAccessibleContract<T>))]
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <-- compiler error
interface IRandomWriteAccessible<T> { … }
[ContractClassFor(typeof(IRandomWriteAccessible<T>))]
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <-- compiler error
sealed class IRandomWriteAccessibleContract<T> : IRandomWriteAccessible<T> { … }
似乎类型参数不能与属性一起使用。
我如何为我的通用接口编写合同?或者这对于代码合约来说是不可能的吗?
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; }
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如此问题中的其他评论所提到的,您应该从属性使用中删除通用类型标识符,因为它无法在编译时解析:
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 的原因是
Blah
不是一个类。如果您可以通过指定
T
的值来为具体类创建一个接口,即使我确信这不是最优的。Good question, but you can see the technical reasons behind this limitation, right?
The reason that you can't specify the ContractClass is because
Blah<T>
is not a class.If you can make an interface for a concrete class by specifying a value for
T
, even though I'm sure this is sub-optimal.