2011-12-10 92 views
2

例如:如何通過在物體快速初始化「這個」參考

List<Projects> projectList = new List<Projects> 
{ 
    new Project 
    { 
     id = 100500, 
     Subprojects = new List<Subproject> 
     { 
      new Subproject { Project = "**Need to pass pointer on the project**" }, 
     } 
    } 
} 

如何能夠通過這個指針?

這是一個關於語法的問題,我清楚地知道可以用另一種方式來做。

回答

2

你不能這樣做在一個聲明:該指針(實際上,參考),你想分配給Project你要分配的時間不分配它。您需要使用中間變量 - 例如,像這樣:

Project p; 
List<Projects> projectList = new List() { 
    p = new Project() { 
     id = 100500 
    , Subprojects = new List<Subproject>() 
    } 
}; 
p.Subprojects.Add(
    new Subproject { Project = p } 
); 
3

如何爲每個類添加標準函數/構造函數?

例如:

List<Project> cProjects = new List<Project> { new Project(100500) }; 

public class Project 
{ 
    public Project(int id) 
    { 
     this.id = id; 
     Subprojects = new List<Subproject> { new Subproject(this) }; 
    } 
    public int id; 
    public List<Subproject> Subprojects; 
} 
public class Subproject 
{ 
    public Subproject(Project project) 
    { 
     this.Project = project; 
    } 

    public Project Project; 
}