2010-09-04 71 views
-3

任何人都可以告訴我這個控制檯應用程序做了什麼嗎?究竟發生了什麼?c中的獲取者和安裝者#

此外,還有錯誤。你能解決他們嗎?

public class Program 
{ 
    static void Main(string[] args) 
    { 
     Name n = new Name[5]; // error 
     n[0] = new Name(0); //error 
     n[0] = "hgfhf"; //is this possible in this program? 
     string nam = n[0]; 
    } 
} 
public class Name 
{ 
    private string[] name; 
    private int size; 
    public Name(int size) 
    { 
     this.name = new string[size]; 
     this.size = size; 
    } 
    public string this[int pos] // what does this mean? 
    { 
     get 
     { 
      return name[pos]; 
     } 
     set 
     { 
      name[pos] = value; 
     } 
    } 
} 
+4

糟糕的標點符號... – RedFilter 2010-09-04 09:42:34

+4

請刪除txtspk,它只會讓你很難讀出你想說的話。 – Guffa 2010-09-04 09:42:55

+6

如果你想使用StackOverflow,請在你的問題上付出一些努力。我只是*爲你翻譯它;不要使用'文本'的發言,並至少嘗試使用正確的拼寫和標點符號。 – GenericTypeTea 2010-09-04 09:44:03

回答

2

這是一個indexer property。這就像一個正常的屬性,但它可以讓你使用[]語法就可以了:

public class Program 
{ 
    static void Main(string[] args) 
    { 
     // Create a Name instance by calling it's constructor 
     // capable of storing 1 string 
     Name n = new Name(1); 

     // Store a string in the name 
     n[0] = "hgfhf"; 

     // Retrieve the stored string 
     string nam = n[0]; 
    } 
} 

public class Name 
{ 
    private string[] names; 
    private int size; 

    public Name(int size) 
    { 
     // initialize the names array for the given size 
     this.names = new string[size]; 

     // store the size in a private field 
     this.size = size; 
    } 

    /// <summary> 
    /// Indexer property allowing to access the private names array 
    /// given an index 
    /// </summary> 
    /// <param name="pos">The index to access the array</param> 
    /// <returns>The value stored at the given position</returns> 
    public string this[int pos] 
    { 
     get 
     { 
      return names[pos]; 
     } 
     set 
     { 
      names[pos] = value; 
     } 
    } 
} 
0
Name n = new Name[5]; //this is declaration error 

- >你需要申報類名的數組。

聲明爲:

Name[] n = new Name[5]; 


public string this[int pos] {} 

這意味着你已經定義了一個索引屬性和索引允許classstruct的情況下被編入索引,就像陣列。

現在您正在分配一個字符串值(string nam = n[0]),因爲該屬性已被定義,所以這是正確的。

+0

撕裂者,單擊編輯並查看右側的幫助列 – 2010-09-04 09:59:26

0
Name n = new Name[5];//error 

可變n是的Name單個實例的引用,所以你不能把一個陣列中的它。使用Name[]作爲變量的類型。

n[0] = new Name(0);//error 

當您將變量設爲數組時,此錯誤將消失。

n[0] = "hgfhf";//is this possible in this program?? 

不,這會試圖用字符串替換Name實例。如果你想要把字符串中使用雙索引Name例如,一個索引來訪問項目在數組中,和一個索引來訪問Name實例的索引器屬性:

n[0][0] = "asdf"; 

(然而,由於你爲Name實例指定一個大小爲零,這將導致IndexOutOfRangeException

public string this[int pos]//wt this means???? 

這是索引屬性。它是一個帶有參數的屬性,通常用於訪問項目,就好像對象是數組一樣。