2013-11-26 40 views
1

如何才能使方法计算出listOfNodes对象的总和?我正在用foreach语句如计算ListNode中对象的总和

foreach(int s in listOfNodes) 
    sum += s; 

获取所有节点但它没有奏效。

它说:

Error 1 foreach statement cannot operate on variables of type 'ConsoleApplication1.Program.List' because 'ConsoleApplication1.Program.List' does not contain a public definition for 'GetEnumerator' C:\Users\TBM\Desktop\I\ConsoleApplication1\ConsoleApplication1\Program.cs 24 13 ConsoleApplication1 

我的代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      List listOfNodes = new List(); 

      Random r = new Random(); 
      int sum = 0; 
      for (int i = 0; i < 10; i++) 
      { 
       listOfNodes.addObjects(r.Next(1, 100)); 

      } 
      listOfNodes.DisplayList(); 

       Console.ReadLine(); 
     } 

     class ListNode 
     { 
      public object inData { get; private set; } 
      public ListNode Next { get; set; } 

      public ListNode(object dataValues) 
       : this(dataValues, null) { } 

      public ListNode(object dataValues, 
       ListNode nextNode) 
      { 
       inData = dataValues; Next = nextNode; 
      } 
     } // end class ListNode 

     public class List 
     { 
      private ListNode firstNode, lastNode; 
      private string name; 

      public List(string nameOfList) 
      { 
       name = nameOfList; 
       firstNode = lastNode = null; 
      } 

      public List()//carieli list konstruktori saxelis "listOfNodes" 
       : this("listOfNodes") { } 


      public void addObjects(object inItem) 
      { 
       if (isEmpty()) 
       { firstNode = lastNode = new ListNode(inItem); } 
       else { firstNode = new ListNode(inItem, firstNode); } 
      } 

      private bool isEmpty() 
      { 
       return firstNode == null; 
      } 

      public void DisplayList() 
      { 
       if (isEmpty()) 
       { Console.Write("Empty " + name); } 
       else 
       { 
        Console.Write("The " + name + " is:\n"); 

        ListNode current = firstNode; 

        while (current != null) 
        { 
         Console.Write(current.inData + " "); 
         current = current.Next; 
        } 
        Console.WriteLine("\n"); 
       } 
      } 

     }//end of class List 
    } 
} 
+0

你知道'.NET'已经有'LinkedList '。我想这是某种学校作业项目,稍后你会了解它们。 – ja72

回答

1

由于错误消息说,你需要为了在一些实施GetEnumeratorforeach。因此,实施GetEnumerator

public IEnumerator GetEnumerator() 
{ 
    ListNode node = firstNode; 
    while (node != null) 
    { 
     yield return node; 
     node = node.Next; 
    } 
} 

你现在可以有你的List类实现IEnumerable接口也一样,如果你想要的。

另一种方法是不使用foreach循环,而是使用while循环,因为我在这里做,或者你在DisplayList方法一样。