總結:CLR Via C#(第九章):屬性與索引器

來源:互聯網
上載者:User

屬性:

1、 屬性可以標記任意的存取修飾詞,並且可以定義在介面中;

2、 屬性類型不能是void類型;

3、 屬性的Get訪問器不接受參數;

4、 c#不允許出現泛型屬性;

5、 屬性裡訪問器的可訪問性預設跟屬性相同,也可以自行限定;

public class SomeType

    {

        public string Name

        {

            get { return null; }

            protected set { }

        }

}

 

屬性與欄位的區別:

1、 屬性與欄位相似,但屬性是方法;

2、 屬性方法也會拋出異常,欄位的訪問則永遠不會拋出異常;

3、 屬性不能作為out或ref參數傳遞給方法,欄位可以;

 

索引器:

索引器就是一類特殊的屬性,通過它們你就可以像引用數組一樣引用自己的類。顯然,這一功能在建立集合類的場合特別有用,而在其他某些情況下,比如處理大型檔案或者抽象某些有限資源等,能讓類具有類似數組的行為當然也是非常有用的。

 

1、 索引器至少擁有一個參數,也可以擁有多個參數;

2、 參數和傳回型別可以是任意的資料類型(除了void);

3、 C#只允許在對象的執行個體上定義索引器;

4、 不允許出現相同參數集的索引器;

      public Accessable_Test this[int i]

        {

            get { return accesses[i]; }

            set { accesses[i] = value; }

        }

        public Accessable_Test this[string str]

        {

            get { return null; }          

            set { }

        }

        // Error:已經定義了具有相同參數類型的成員

        //public string this[int i]

        //{

        //    get { return null; }

        //    set { }

        //}

 

屬性和索引器的區別:

1、 類的每一個屬性都必須擁有唯一的名稱,而類裡定義的每一個索引器都必須擁有唯一的簽名(signature)或者參數列表(這樣就可以實現索引器重載)。

2、屬性可以是static(靜態)而索引器則必須是執行個體成員。

public class Accessable_Test

    {

        List<Accessable_Test> accesses = new List<Accessable_Test>();

        private int m_id;

        public int ID

        {

            get { return m_id; }

            set { m_id = value; }

        }

        //private string m_str;

        // Error:已經包含了ID的定義

        //public string ID

        //{

        //    get { return m_str; }

        //}

        private string m_name;

        public string Name

        {

            get { return m_name; }

            set { m_name = value; }

        }

        public Accessable_Test this[int i]

        {

            get { return accesses[i]; }

            set { accesses[i] = value; }

        }

        public Accessable_Test this[string str]

        {

            get { return null; }          

            set { }

        }

        // Error:已經定義了具有相同參數類型的成員

        //public string this[int i]

        //{

        //    get { return null; }

        //    set { }

        //}

    }

 

文章借鑒:http://www.cnblogs.com/wjfluisfigo/archive/2009/05/04/1448079.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.