2016-08-22 46 views
-4

我有點困惑這個相當典型的錯誤。我的代碼如下。我正在嘗試將項目添加到列表中。非靜態字段需要對象引用。列表<>

編譯器是說我需要非靜態字段的對象引用,但我不能讓類的靜態,因爲我沒有返回值...?

public class ApplicantData 
     { 
      public string Salutation { set; get; } 
      public string FirstName { set; get; } 
      public string LastName { set; get; } 
     } 

     public class ApplicantList : List<ApplicantData> 
     { 
      public void Add(string salutation, string firstName, string lastName) 
      { 
       var data = new ApplicantData 
       { 
        Salutation = salutation, 
        FirstName = firstName, 
        LastName = lastName 

       }; 
       this.Add(data); 
      } 
     } 

以上被稱爲經:

List ApplicantsDetailsData = ApplicantList.Add(salutation, firstname, lastname); 

我相信答案一定是顯而易見的......

+1

您正在靜態調用ApplicantList.Add()。你需要一個ApplicantList的實例,而不是類的引用(否則你實際上沒有一個列表來添加項目)。 – BoltClock

+0

您需要ApplicantList的實例。您所呼叫的Add方法,因爲它是一個靜態方法 – Steve

+1

請注意,您也返回'void',要指定一個'List' – technikfischer

回答

2

您需要一個實例的列表中添加東西。現在你只有概念的列表。你有零個清單。例如:

var list = new ApplicantList(); 
list.Add("foo", "bar", "blap"); 

然而,它通常是一個壞/混淆移動子類List<T>,IMO。

+0

恐怕要編輯的問題,這裏是[爲什麼從列表<繼承>是壞的(http://stackoverflow.com/q/21692193/1997232)。 – Sinatr

0

您需要創建ApplicationList實例(!)

ApplicantList applicantsDetailsData = new ApplicantList(); 
applicantsDetailsData.Add(salutation, firstname, lastname); 
1

您正在嘗試使用ApplicantList.Add像一個靜態方法。

您首先需要創建ApplicantList類型的對象,而對象調用Add。你不能直接在課堂上調用它,因爲它不是靜態的。

0

ApplicationList是類型(繼承自List),而不是該類型的實例。您只能在類的實例上調用實例成員(不帶static關鍵字的函數)。

ApplicationList ApplicantsDetailsData = new ApplicationList(); 
applicationList.Add(salutation, firstname, lastname); 
相關問題