分配变量并检查值?

时间:2013-11-12 14:31:45

标签: c# .net

有可能这样的事情:

var userAggregazione;
if (userAggregazione = YouTube.Actions.IsAccessTokenValid() != null)
{
}

IsAccessTokenValid()会返回userAggregazione个实例或null。因此,在if中,我想设置var userAggregazione,并检查它是否为null

有可能吗?

3 个答案:

答案 0 :(得分:3)

不确定我是否理解,但让我尝试:

var userAggregazione = YouTube.Actions.IsAccessTokenValid();
if (userAggregazione == null)
{
   // userAggregazione is null - do something
}
else
{
   // it is not null - do something
}

答案 1 :(得分:2)

如果在赋值周围有一个额外的括号,它将起作用,因此它将在!=比较之前得到评估。

MyClass userAggregazione;
if ((userAggregazione = YouTube.Actions.IsAccessTokenValid()) != null)
{}

EDIT2: 我假设这个例子是简化的,因为通常你应该这样做是为了清楚:

//my style preference is also to not use 'var' anyway
//when getting value from a function
//because it's not clear what the type is.
MyClass userAggregazione = YouTube.Actions.IsAccessTokenValid();
if (userAggregazione != null)
{}

答案 2 :(得分:0)

是的,你需要添加一些大括号:

if ((userAggregazione = YouTube.Actions.IsAccessTokenValid()) != null)

确保IsAccessTokeValid不会抛出任何异常