gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:22:09 25 4
gpt4 key购买 nike

当我有这样的声明时:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com