c# - C#中的对象初始化

标签 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() 中我如何初始化学生?

最佳答案

首先使其可访问:

public student Student { get; set; }

然后是这样的:

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

请注意,如果该属性是只获取的:

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

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

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

关于c# - C#中的对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1584270/

相关文章:

c# - 如何从类中获取私有(private)静态字段的值?

c# - 用于通用访问的 IDataReader

swift - 为什么我不能从方法更改对象属性

C# 异步任务 : do all participating methods have to be async as well?

c# - WPF UserControl 如何继承 WPF UserControl?

c# - 传递凭据适用于 WebRequest,但不适用于 HttpClient

c# - 使用运行时已知的类型创建委托(delegate)

c# - WPF支持触摸屏还是多点触摸屏?

javascript - 需要有关 javascript oops 的帮助

python - Tensorflow 对象检测 - 避免重叠框