C# 屬性、索引


屬性(property: 

public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}    

 

簡寫為:

public string Name { set; get;}

 

索引器(index):

索引器為C#程序語言中淚的一種成員,它是的對象可以像數組一樣被索引,使程序看起來更直觀,更容易編寫。

索引器和數組比較:

(1)索引器的索引值(Index)類型不受限制

(2)索引器允許重載

(3)索引器不是一個變量

索引器和屬性的不同點

(1)屬性以名稱來標識,索引器以函數形式標識

(2)索引器可以被重載,屬性不可以

(3)索引器不能聲明為static,屬性可以

 

要聲明類或結構上的索引器,請使用this關鍵字,例如: 

public int this[int index] //聲明索引器

{

// get and set 訪問

}

 

 索引器的修飾符有:new、public、protected、internal、private、virtual、sealed、override、abstract和extern。

 

當索引器聲明包含extern修飾符時,稱該索引器為外部索引器。因為外部索引器聲明不提供任何實際的實現,所以它的每個訪問器聲明都由一個分號組成。

 

索引器的簽名由其形參的數量和類型組成。它不包括索引器類型或形參名。如果在同一類中聲明一個以上的索引器,則它們必須具有不同的簽名。

 

索引器值不歸類為變量;因此,不能將索引器值作為ref或out參數來傳遞。

 

索引必須是實例成員。

 

索引器使用示例:

using System;
class IndexerRecord
{
    private string [] data = new string [6];
    private string [] keys  = {
        "Author", "Publisher", "Title",
        "Subject", "ISBN", "Comments" 
        }; 
     
    //注:程序中用了兩種方法來索引:
    //一是整數作下標,二是字符串(關鍵詞名)作下標
    public string this[ int idx ]
    {
        set
        {
            if( idx >= 0 && idx < data.Length )
                data[ idx ] = value;
        }
        get
        {
            if( idx >= 0 && idx < data.Length )
                return data[ idx ];
            return null;
        }
    }
    public string this[ string key ]
    {
        set
        {
            int idx = FindKey( key );
            this[ idx ] = value;
        }
        get
        {
            return this[ FindKey(key) ];
        }
    }
    private int FindKey( string key )
    {
        for( int i=0; i<keys.Length; i++)
            if( keys[i] == key ) return i;
        return -1;
    }
    static void Main()
    {
        IndexerRecord record = new IndexerRecord();
        record[ 0 ] = "馬克-吐溫";
        record[ 1 ] = "Crox出版公司";
        record[ 2 ] = "湯姆-索亞歷險記";
        Console.WriteLine( record[ "Title" ] );
        Console.WriteLine( record[ "Author" ] );
        Console.WriteLine( record[ "Publisher" ] );
        
        Console.ReadKey(true);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM