参考以下SE答案.
写作时
A = A ?? B;
Run Code Online (Sandbox Code Playgroud)
它是一样的
if( null != A )
A = A;
else
A = B;
Run Code Online (Sandbox Code Playgroud)
这是否意味着
if( null == A ) A = B;
Run Code Online (Sandbox Code Playgroud)
性能明智吗?
或者我可以假设编译器在??表示相同对象时优化代码?
我经常看到这样的言论:
int? a = 5;
//...other code
a ??= 10;
Run Code Online (Sandbox Code Playgroud)
??=第二行是什么意思?我以前见过??用于空合并,但我从未见过它与等号一起使用。
我正在查看我刚才写的一些代码,并意识到我在C#中对赋值运算符做了一个假设.这是有问题的代码行(它按预期工作):
pointsChecked = pointsChecked ?? new List<Point>();
Run Code Online (Sandbox Code Playgroud)
pointsChecked是一个List,指定为递归函数的参数.它是具有默认值的默认参数null.我想要做的是初始化一次然后构建我已经检查过的点集合,因此它应该只在第一次迭代期间初始化.
我的假设是C#可以防止自我分配,就像C++ 在过载时operator= 应该提供一个后卫一样(即if(this == &rightHandSide) return *this;).但是,我无法找到任何明确说明C#属实的资源.
我发现的最接近的例子是关于null-coalescing运算符的这个问题,如果不是,那么它似乎会将对象分配回自身null.在这个例子中,没有人说过自我指派的任何内容,但我想确定这不是一个坏的做法,并且没有负面的副作用.
在MSDN上搜索我也发现(根据我的理解释义)右侧的值被复制到左侧的值并返回.因此,我再次不确定自我指派是否是一件坏事.
我知道我可以做到以下更安全:
if(pointsChecked == null)
{
pointsChecked = new List<Point>();
}
Run Code Online (Sandbox Code Playgroud)
但我宁愿理解自我分配的实际情况.
可能重复:
C#中两个问号共同意味着什么?
我试图理解这个判断的作用:"??" 意思?如果if-statment,这是som类型吗?
string cookieKey = "SearchDisplayType" + key ?? "";
Run Code Online (Sandbox Code Playgroud) 我正在看ASP.NET MVC 1.0生成的代码,并且想知道; 双重问号意味着什么?
// This constructor is not used by the MVC framework but is instead provided for ease
// of unit testing this type. See the comments at the end of this file for more
// information.
public AccountController(IFormsAuthentication formsAuth, IMembershipService service)
{
FormsAuth = formsAuth ?? new FormsAuthenticationService();
MembershipService = service ?? new AccountMembershipService();
}
Run Code Online (Sandbox Code Playgroud)
在下面的代码片段company.ParentID是一个int?和parrent引用类型.此代码是语法错误.无论如何要解决这个内联条件?
company.ParentID = (parent == null ? null: (parent.ID));
可能重复:
C#中两个问号共同意味着什么?
我刚刚看到下面的代码,并不确定它是什么意思,不能谷歌它因为谷歌省略了 ??
int? x = 32;
int y = x ?? 5;
Run Code Online (Sandbox Code Playgroud)
第二行是某种if else语句,是什么??意思
可能重复:
两个问号一起在 C# 中意味着什么?
的作用是什么??这个 C# 语句中的意思是什么?
int availableUnits = unitsInStock ?? 0;
Run Code Online (Sandbox Code Playgroud) 今天,我从我的客户端提取代码,我在这一行中收到错误.
throw new Exception($"One or more errors occurred during removal of the company:{Environment.NewLine}{Environment.NewLine}{exc.Message}");
Run Code Online (Sandbox Code Playgroud)
这条线也
moreCompanies = $"{moreCompanies},{databaseName}";
Run Code Online (Sandbox Code Playgroud)
$符号对我来说太奇怪了.这是C#代码.
我在项目中发现了这个新的有趣的代码.它做了什么,它是如何工作的?
MemoryStream stream = null;
MemoryStream st = stream ?? new MemoryStream();
Run Code Online (Sandbox Code Playgroud)