更新时间:2022-10-16 12:16:01
这称为合并。
当this.teacher为NULL时,返回一个新的teacher()对象;
??是空合并运算符 - microsoft reference [ ^ ]
所以一段代码本质上是说返回当前的teacher实例,或者如果当前实例为null,则创建一个
你的示例代码是惯用的C#代码来说if (teacher == null ) // 这是*之前的部分*??合并运算符
{
teacher = new Teacher(); // 这是*之后的部分*合并运算符
}
返回老师;
或返回老师!= null ?老师:(老师= 新老师());
干杯
Andi
Hello guys, could you tell me what is this? I saw this in an article.
public Person Teacher { get { return this.teacher ?? (this.teacher = new Teacher()); } }
I have no idea what is this??
This is called coalescing.
When this.teacher is NULL return a new teacher() object;
?? Is the null coalescing operator - microsoft reference[^]
So the piece of code is essentially saying return the current instance of teacher, or if the current instance is null create one
Your example code is idiomatic C# code to sayif (teacher == null) // this is the part *before* the "??" coalescing operator { teacher = new Teacher(); // this is the part *after* the "??" coalescing operator } return teacher;
Orreturn teacher != null ? teacher : (teacher = new Teacher());
Cheers
Andi