C#中的奇怪运算符 [英] Strange Operator In C#

查看:83
本文介绍了C#中的奇怪运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,伙计们,你能告诉我这是什么意思吗?我在一篇文章中看到了这个。



公共人员老师
{
得到
{
返回this.teacher ?? (this.teacher = new Teacher());
}
}





我不知道这是什么?

解决方案

这称为合并。

当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 say

if (teacher == null)        // this is the part *before* the "??" coalescing operator
{
   teacher = new Teacher(); // this is the part *after* the "??" coalescing operator
}
return teacher;


Or

return teacher != null ? teacher : (teacher = new Teacher());


Cheers
Andi


这篇关于C#中的奇怪运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆