2010-07-30 70 views
2

我想編程一個簡單的員工註冊表,我想使用通用列表來「保存」我創建的人。如何添加至尚未創建的列表。請幫忙!

經理類有一個構造函數和一個方法(見下文)。 構造函數創建List並將方法添加到它,或者應該添加到它。 問題是,我不能像下面這樣做,因爲Visual Studio認爲employeeList在當前上下文中不存在。我怎麼會寫這個?

public EmployeeManager() 
{ 
    List<string> employeeList = new List<string>(); 
} 

public void AddEmployee() 
{ 
    employeeList.add("Donald"); 
} 

回答

12

你需要讓EmployeeList的類的成員變量:

class EmployeeManager 
{ 
    // Declare this at the class level 
    List<string> employeeList; 

    public EmployeeManager() 
    { 
     // Assign, but do not redeclare in the constructor 
     employeeList = new List<string>(); 
    } 

    public void AddEmployee() 
    { 
     // This now exists in this scope, since it's part of the class 
     employeeList.add("Donald"); 
    } 
} 
+0

@Reed善真快。在放棄並輸入我想要做的事情的解釋之前,我在格式化方面努力:) – 2010-07-30 20:45:13

+0

如果列表還沒有被實例化,這仍然會拋出一個空引用。使列表成爲一個懶惰構建的私有財產。 – DevinB 2010-07-30 20:45:40

+0

@devinb只有在使用了另一個構造函數的情況下,因爲它永遠不會拋出null ref。 – 2010-07-30 20:46:59

1

你聲明EmployeeList的作爲類中的一員?

private List<string> employeeList = new List<string(); 

public EmployeeManager() 
{ 

} 

public void AddEmployee() 
{ 
    employeeList.add("Donald"); 
} 
1
List<string> employeeList = new List<string>(); 

public EmployeeManager() 
{ 
} 

public void AddEmployee() 
{ 
    employeeList.add("Donald"); 
} 

,或者交替

List<string> employeeList; 

public EmployeeManager() 
{ 
    employeeList = new List<string>(); 
} 

public void AddEmployee() 
{ 
    employeeList.add("Donald"); 
} 

當你定義它,employeeList生命只在構造函數。一旦它完成,employeeList消失,它的內存被garbabge收集。通過將聲明移動到課堂級別,它可以在對象的整個生命中生活。

1

EmployeeList的一定是你的類

1

的成員聲明添加僱員職能範圍之外的列表。然後如果你在構造函數中實例化它,你會沒事的。

0

你得到這個錯誤的原因是因爲employeeList的範圍只在構造函數中。爲了使用employeeList它必須在更大範圍內進行定義,像這樣:

class EmployeeManager 
{ 
    private List<string> employeeList; 

    public EmployeeManager() 
    { 
     employeeList = new List<string>(); 
    } 

    public void AddEmployee() 
    { 
     employeeList.add("Donald"); 
    } 
} 
0

的問題,你必須與範圍。當構造函數觸發時,它將創建employeeList List,然後退出。此時,employeeList從內存(堆棧)中消失。

你需要的是在類級別這樣的聲明EmployeeList的:

List<string> employeeList = null; 
public EmployeeManager() 
{ 
    employeeList = new List<string>(); 
} 

public void AddEmployee() 
{ 
    employeeList.add("Donald"); 
} 
0

你需要成爲會員級別的變量

public class EmployeeManager 
{ 
    private List<string> _employeeList; 
    public EmployeeManager() 
    { 
     _employeeList = new List<string>(); 
    } 

    public void AddEmployee() 
    { 
     _employeeList.add("Donald"); 
    } 
} 
0

您需要實例化EmployeeManager的範圍可以通過Add方法訪問 - 您只需定義類。

0

您的EmployeeManager類需要一個字段或屬性才能對應employeeList。像這樣:

public class EmployeeManager 
{ 
    private List<string> employeeList; //Create Field 

    public EmployeeManager() 
    { 
    this.employeeList = new List<string>(); 
    } 

    public void AddEmployee() 
    { 
    this.employeeList.Add("Donald"); 
    } 
} 
相關問題