2010-09-04 72 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???? 

这是索引属性。它是一个带有参数的属性,通常用于访问项目,就好像对象是数组一样。