如何在对象快速初始化中传递'this'引用

时间:2011-12-10 20:34:16

标签: c# class generics initialization this

例如:

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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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 }
);