这是什么?运营商在C#中意味着什么? [英] What does ?? operator means in C#?

查看:120
本文介绍了这是什么?运营商在C#中意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
什么做两个问号一起在C#是什么意思?






您好,我一直在寻找在C#MVC 2的一些培训,我发现这个sintax:

 计算机[东西] =东西?真正; 



那么,什么是'?'的意思?


< DIV CLASS =h2_lin>解决方案

这是空合并运算符



据,除非它为null,在这种情况下,它返回第二返回第一个参数。



X?是大致相当于这(除了第一个参数只计算一次):

 如果(X == NULL)
{
结果= Y;
}
,否则
{
结果= X;
}



或者:

 (X == NULL)? Ÿ:X 



这是用于为当值可以为null的默认值有用:

 色色= user.FavouriteColor? defaultColor; 






COALESCE



当在使用LINQ to SQL查询的 ?? 操作符可以翻译向的COALESCE 。例如,这LINQ查询:

  VAR的查询= dataContext.Table1.Select(X => x.Col1 ??默认); 



可能会导致此SQL查询:

  SELECT COALESCE([T0]。[COL1],@ P0)AS [值] 
从[DBO]。[表1] AS [T0]


Possible Duplicate:
What do two question marks together mean in C#?

Hi, I was looking for some trainings of MVC 2 in C# and I found this sintax:

ViewData["something"] = something ?? true;

So, what is that '??' means ?.

解决方案

It's the null-coalescing operator.

It returns the first argument unless it is null, in which case it returns the second.

x ?? y is roughly equivalent to this (except that the first argument is only evaluated once):

if (x == null)
{
     result = y;
}
else
{
     result = x;
}

Or alternatively:

(x == null) ? y : x

It is useful for providing a default value for when a value can be null:

Color color = user.FavouriteColor ?? defaultColor;


COALESCE

When used in a LINQ to SQL query the ?? operator can be translated to a call to COALESCE. For example this LINQ query:

var query = dataContext.Table1.Select(x => x.Col1 ?? "default");

can result in this SQL query:

SELECT COALESCE([t0].[col1],@p0) AS [value]
FROM [dbo].[table1] AS [t0]

这篇关于这是什么?运营商在C#中意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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