2013-11-26 4 views
1

listOfNodes 개체의 합계를 계산하는 방법을 어떻게 만들 수 있습니까? 나는 모든 노드를 얻기 위해ListNode에있는 객체의 합계를 계산하십시오.

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

과 같은 foreach 문을 사용하고 있었지만 작동하지 않았습니다.

은 말한다 :

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

, 당신이 뭔가 이상 foreach하기 위해 GetEnumerator를 구현해야합니다. 그래서, GetEnumerator을 구현 : 이제 당신이 원하는 경우 List 클래스는, 너무 IEnumerable 인터페이스를 구현할 수 있습니다

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

.

대안은 foreach 루프를 사용하지 않고 대신 여기에서했던 것처럼 while 루프를 사용하거나 DisplayList 메소드에서 수행 한 것입니다.

관련 문제