Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

.net - 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; }
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<>))] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...