??运算符

cherish_55 2012-06-12 09:36:43
c#中这样一个判断条件:if (IsTa ?? false)
我试了一下只有IsTa 为true的情况下,才会执行这个分支,这是什么意思?
...全文
151 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
叫我三三 2012-06-12
  • 打赏
  • 举报
回复
object isnull=null;

isnull??"show"
等价于
isnull==null?"show":isnull
zhujiawei7 2012-06-12
  • 打赏
  • 举报
回复
IsTa ?? false
IsTa为null时,返回false;不为null时,返回IsTa
mathieuxiao 2012-06-12
  • 打赏
  • 举报
回复
IsTa ?? false的意思是如果IsTa为null值,则该表达式的结果就是false,如果不为null,则使用IsTa的值作为表达式的结果。

1. IsTa 为null时,IsTa ?? false ---》 false
2. IsTa 为false时,IsTa ?? false ---》 false
3. IsTa为true时,IsTa ?? false的结果就是IsTa的值,即为true,所以会去执行{}中的内容
ParanoidKing 2012-06-12
  • 打赏
  • 举报
回复
a = b ?? c
等同于
if(b == null)
a = c;
else
a = b;
宝_爸 2012-06-12
  • 打赏
  • 举报
回复
?? Operator (C# Reference)

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}

static string GetStringValue()
{
return null;
}

static void Main()
{
// ?? operator example.
int? x = null;

// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;

// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.
int i = GetNullableInt() ?? default(int);

string s = GetStringValue();
// ?? also works with reference types.
// Display contents of s, unless s is null,
// in which case display "Unspecified".
Console.WriteLine(s ?? "Unspecified");
}
}

参考:
http://msdn.microsoft.com/en-us/library/ms173224.aspx

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧