ContractClassAttribute 类
2013/3/11
指定一个单独的类型包含此类型的代码协定。
Namespace:
System.Diagnostics.Contracts
程序集: mscorlib(位于 mscorlib.dll 中)
ContractClassAttribute 类型公开以下成员。
| 名称 | 说明 | |
|---|---|---|
![]() | Equals | 基础结构。 返回一个值,该值指示此实例是否与指定的对象相等。 (从 Attribute 继承。) |
![]() | Finalize | 允许 Object 在垃圾回收器回收该对象之前尝试释放资源并执行其他清理操作。 (从 Object 继承。) |
![]() | GetHashCode | 返回此实例的哈希代码。 (从 Attribute 继承。) |
![]() | GetType | 获取当前实例的 Type。 (从 Object 继承。) |
![]() | Match | 当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。 (从 Attribute 继承。) |
![]() | MemberwiseClone | 创建当前 Object 的浅表副本。 (从 Object 继承。) |
![]() | ToString | 返回一个字符串,它表示当前的对象。 (从 Object 继承。) |
下面的示例演示如何使用 ContractClassAttribute 特性来指定 IArray 接口的协定包含在 IArrayContracts 类中。
using System; using System.Diagnostics.Contracts; // An IArray is an ordered collection of objects. [ContractClass(typeof(IArrayContract))] public interface IArray { // The Item property provides methods to read and edit entries in the array. Object this[int index] { get; set; } int Count { get; } // Adds an item to the list. // The return value is the position the new element was inserted in. int Add(Object value); // Removes all items from the list. void Clear(); // Inserts value into the array at position index. // index must be non-negative and less than or equal to the // number of elements in the array. If index equals the number // of items in the array, then value is appended to the end. void Insert(int index, Object value); // Removes the item at position index. void RemoveAt(int index); } [ContractClassFor(typeof(IArray))] internal abstract class IArrayContract : IArray { int IArray.Add(Object value) { // Returns the index in which an item was inserted. Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < ((IArray)this).Count); return default(int); } Object IArray.this[int index] { get { Contract.Requires(index >= 0); Contract.Requires(index < ((IArray)this).Count); return default(int); } set { Contract.Requires(index >= 0); Contract.Requires(index < ((IArray)this).Count); } } public int Count { get { Contract.Requires(Count >= 0); Contract.Requires(Count < ((IArray)this).Count); return default(int); } } void IArray.Clear() { Contract.Ensures(((IArray)this).Count == 0); } void IArray.Insert(int index, Object value) { Contract.Requires(index >= 0); Contract.Requires(index <= ((IArray)this).Count); // For inserting immediately after the end. Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) + 1); } void IArray.RemoveAt(int index) { Contract.Requires(index >= 0); Contract.Requires(index < ((IArray)this).Count); Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) - 1); } }


