2010-09-04 71 views
0

这个程序有错误,任何人都可以解决这个问题?c中的索引器程序#

class TempRecord 
{ 
    // Array of temperature values 
    private float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 
             61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; 
    private int[] d= new int[10]{4,5,5,4,4,43,2,2,5,3}; 
    // To enable client code to validate input 
    // when accessing your indexer. 
    //public int Length 
    //{ 
    // get { return temps.Length; } 
    //} 
    // Indexer declaration. 
    // If index is out of range, the temps array will throw the exception. 
    public float this[int index] 
    { 
     get 
     { 
      return temps[index]; 
     } 

     set 
     { 
      temps[index] = value; 
     } 
    } 
    public int this[int index] 
    { 
     get 
     { 
      return d[index]; 
     } 

     set 
     { 
      d[index] = value; 
     } 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     TempRecord tempRecord = new TempRecord(); 
     // Use the indexer's set accessor 
     tempRecord[3] = 58.3F; 
     tempRecord[5] = 60.1F; 



     // Use the indexer's get accessor 
     for (int i = 0; i < 10; i++) 
     { 
      System.Console.WriteLine("Element #{0} = {1}", i, tempRecord[i]); 
     } 
     Console.WriteLine(tempRecord[2]); 
     // Keep the console window open in debug mode. 
     System.Console.WriteLine("Press any key to exit."); 
     System.Console.ReadKey(); 

    } 
} 
+7

不要只是说有错误。告诉我们它在哪里以及错误是什么。 – GenericTypeTea 2010-09-04 11:53:29

+4

SO上有答案。你能找到他们吗? – StuartLC 2010-09-04 11:55:13

+1

我们可以解决它,但你怎么样,因为这是你的问题不是我们的?你的[其他问题](http://stackoverflow.com/questions/3641695/getters-and-setters-in-c-closed)暗示了一种不受欢迎的态度。这是一种寻求他人工作而不表现出任何动机和个人暗示的人的态度。所以除非这种态度改变,否则你的问题可能会被社区所关闭。 – 2010-09-04 12:07:15

回答

1

类型 'ConsoleApplication1.TempRecord' 已经定义了一个名为 '本' 具有相同的参数类型成员

那是你的错误?

如果是 - 阅读它说的=)您有两个this成员,也称为Indexers,具有相同的方法签名。具体来说:

public float this[int index] 
public int this[int index] 

请记住,对于消歧,不考虑返回类型。您需要删除一个Completley或将其更改为一个方法,而不是索引器。

试想一下,如果它允许你有下面的代码:

var record = new TempRecord(); 
object value = record[3]; 

哪些索引应该在这里叫什么名字?返回float的那个或返回int的那个。是的,这个例子是人为设计的,但从语言设计和编译器实现的角度来看,它是完全有效的,因此你不能通过返回类型重载。

1

由于GenericTypeTea说,说你有一些错误是太模糊,以期望任何形式的综合反应。然而,马上我可以告诉你,你试图仅仅基于返回类型来重载索引器属性,这在C#中是不可能的(或者我知道的任何多态语言)。另外,同时提供数组大小和初始化程序列表同时要求维护头疼。此代码编译是因为初始化程序列表中元素的数量和大小匹配,但如果您更改一个而忘记更改另一个,则会开始出现编译器错误。就个人而言,如果您使用的是初始化程序列表,我会建议使用空括号,但是我认为可以根据个人喜好进行划分。