英文:
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<User>(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<User>(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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论