只有在条件为真时,才能访问仅存在于条件内的对象吗?

huangapple go评论96阅读模式
英文:

Can I access an object that only exists within the condition in an if the condition is true?

问题

我正在寻找类似于这样的东西。

if (obj is User user)
{
    user.FirstName = ...
}

现在我想要相同的结果,只是我要进行空值检查,例如。
目前,我必须执行以下操作。

User user;
if ((user = dbContext.Get<User>(id)) != null)
{
    user.FirstName = ...
}

有没有办法在没有顶部一行的情况下获得相同的结果?

英文:

I am looking for something that resembles this.

if(obj is User user)
{
    user.FirstName = ...
}

Now I want the same only that I make a null check for example.
Currently I have to do the following.

User user;
if ((user = dbContext.Get&lt;User&gt;(id)) != null)
{
    user.FirstName = ...
}

Is there any way to get to the same result without the top row?

答案1

得分: 2

你可以简单地将这两种语法结合起来。现有的 is 已经执行了 null 检查。

if (dbContext.Get<User>(id) is User user)
{
    user.FirstName = ...
}

要了解更多信息,请查看 C# 编译器如何转换 is 语法。您可以在 SharpLab 上看到空值检查的实际操作。

英文:

You can just combine the two syntaxes. The existing is already does a null check.

if (dbContext.Get&lt;User&gt;(id) is User user)
{
    user.FirstName = ...
}

For more info, see how the C# compiler translates the is syntax. You can see the null check in action on SharpLab.

huangapple
  • 本文由 发表于 2023年5月24日 22:00:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定