1. 程式人生 > >c# .net介面協定Contract

c# .net介面協定Contract

1.背景

學習以及研究協定Contract

2.程式碼

(1)介面程式碼

    [ContractClass(typeof(PersonContract))]
    public interface IPerson
    {
        string FirstName { get; set; }
        string LastName { get;set; }
        int Age { get;set; }
        void ChangeName (string firstName,string lastName );
    }

(2)協定規則程式碼(對介面成員變數進行協定限制)

[ContractClassFor(typeof(IPerson))]
    public abstract class PersonContract:IPerson
    {
        string IPerson.FirstName
        {
            get { return Contract.Result<string>(); }
            set { Contract.Requires(value != null); }
        }
        string IPerson.LastName
        {
            get { return Contract.Result<string>(); }
            set { Contract.Requires(value != null); }
        }
        int IPerson.Age
        {
            get
            {
                Contract.Ensures(Contract.Result<int>()>=0 &&
                    Contract.Result<int>() < 121);
                return Contract.Result<int>();
            }
            set
            {
                Contract.Requires(value >= 0 && value<123);
            }

(3)介面實現類程式碼

 public class Person:IPerson
    {
        public Person(string firstName,string lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age {get; set;}
        public void ChangeName(string firstName, string lastName)
        {
            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

(4)新建物件,測試並使用

       Person pe=new Person("111",null)

      可以發現,定義好的規則並未生效。經查詢,需要安裝外掛,並設定專案屬性,具體細節見https://www.cnblogs.com/TBW-Superhero/p/7151085.html

(5)在正確設定後,再次測試呼叫   var pp = new Person("132", null);

可發現,該新建物件失敗,進入異常,異常資訊為:

“System.Diagnostics.Contracts.__ContractsRuntime.ContractException”型別的未經處理的異常在 xxxx.exe 中發生“” 

 “其他資訊: 前置條件失敗: value != null”

 

至此,正確的設定了協定併成功起效。