C#中的对象初始化

时间:2009-10-18 07:41:05

标签: c# .net object initialization

当我声明如下:

class Professor
{
  string profid;
  public string ProfessorID
  {
     get { return profid;}
     set { profid=value;}
  }

  student st;

}


class student
{
  string name;
  string id;
  public string Name
  {
     get  { return name;}
     set  { name=value; } 
  }

 public string StudentID
 {
   get { return id;}
   set { id=value; }
 }

}


public void GetDetails()
{
  Professor prf=new Professor(){ ProfessorID=1, how to initialize student here?};

}

在GetDetails()内部,我如何初始化学生?

5 个答案:

答案 0 :(得分:5)

首先让它可以访问:

public student Student { get; set; }

然后像:

Professor prf = new Professor()
{
    ProfessorID = "abc",
    Student = new student { Name = "Marc", StudentID = "def" }
};

请注意,如果属性为get-only:

private readonly student _student = new student();  
public student Student { get { return _student; }}

然后您可以使用替代语法(设置属性而不尝试更改学生参考):

Professor prf = new Professor()
{
    ProfessorID = "abc",
    Student = { Name = "Marc", StudentID = "def" }
};

答案 1 :(得分:3)

您的Professor课程需要为学生设置属性设置器,此时您可以写信:

public void GetDetails()
{
    Professor prf = new Professor { 
        ProfessorID = "1", 
        Student = new Student { Name = "Jon", StudentID = "1" }
    };    
}

如果没有该属性,Professor类中的任何内容都不会设置st变量。

请注意,因为在这两种情况下我们只使用无参数构造函数,所以我从对象初始值设定项中删除了显式()

进一步说明:自动实现的属性可以缩短您的代码:

class Professor
{
    public string ProfessorID { get; set; }
    public Student Student { get; set; }
}

class Student
{
    public string Name { get; set; }
    public string StudentID { get; set; }
}

答案 2 :(得分:1)

你应该让教授的学生成为学生:

class Professor
{
    string profid;
    public string ProfessorID
    {
        get { return profid; }
        set { profid = value; }
    }

    student st;

    public student Student { // New property
        get { return st; }
        set { st = value; }
    }
}


class student
{
    string name;
    string id;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public string StudentID
    {
        get { return id; }
        set { id = value; }
    }

}


public void GetDetails(){
    Professor prf=new Professor(){ ProfessorID="1", Student = new student()};
}

答案 3 :(得分:1)

您需要教授

中的学生访问者
class Professor
{
  string profid;
  public string ProfessorID
  {
     get { return profid;}
     set { profid=value;}
  }

  public Student {
     get { return st;}
     set { st=value;}
  }

  student st;

}


public void GetDetails()
{
  Student s = new Student();
  s.StudentId = someId;
  s.name = someName;
  Professor prf = new Professor { ProfessorID=1, Student = s;};
}

但是,你现在的模特是1名教授:1名学生,你确定这是你想要的吗?

答案 4 :(得分:0)

跟进约翰的回答:

您需要括号,而不是括号,但公共构造函数通常是正确的方法。另一种方法是使用公共属性的无参数构造函数。