2012-11-17 124 views
0

我上課同義詞,如下:如何在課堂上使用List

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml.Linq; 


namespace Examples.NET 
{ 
    public class Synonym 
    { 
     private string _kata; 
     private List<string> _sinonim; 

     public String Kata 
     { 
      get { return _kata; } 
     } 
     public List<string> Sinonim 
     { 
      get 
      { 
       return _sinonim; 
      } 
     } 

     public Synonym(string kata) 
     { 
      _kata = kata; 
      List<string> _sinonim = new List<string>(); 

      XDocument xDoc = XDocument.Load("http://www.stands4.com/services/v2/syno.php?uid=2319&tokenid=LSRyvL5mGsHpEi4&word=" + kata); 
      var sinonim = from isi in xDoc.Descendants("result") 
          select new 
          { 
           sinom = isi.Descendants("synonyms").First().Value 
          }; 
      foreach (var s in sinonim) 
      { 
       _sinonim.Add(s.sinom); 
      } 
     } 

    } 
} 
主程序

,我有下面的代碼:

Synonym Syn = new Synonym("buy"); 

System.Console.WriteLine(Syn.Kata); 

var sinom = from s in Syn.Sinonim 
      select s; 
foreach (var item in sinom) 
{ 
    System.Console.WriteLine("data: " + item); 
} 

,但有錯誤:主程序:「FROM S IN ..... SELECT S「 =========== >>值不能爲空。和參數名稱:源

我猜

public List<string> Sinonim 
    { 
    get{ return _sinonim;} 
    } 

回答

1

這將表明你的私人列表變量從未被分配,它是不是有錯誤。

List<string> _sinonim = new List<string>();

這隱藏了私有實例,因爲該名稱是相同的。在構造該行改成這樣,它應該工作

_sinonim = new List<string>();

+0

謝謝,...一個很好的答案 –