【问题标题】:I need to know what a ? mean in this if statement ? asp.net core 2我需要知道什么?在这个 if 语句中是什么意思? ASP.NET 核心 2
【发布时间】:2018-06-20 08:55:20
【问题描述】:

任何机构都可以帮助我处理此代码。我已经在 asp.net MVC c# 中编写了这段代码,但我不知道为什么要使用?在 if 语句逻辑中。我想知道booking是什么意思?.UserID ??

public async Task<IActionResult> Details(int id)
{
    //get the user who already logged in
    IdentityUser user = await 
    _userManagerService.FindByNameAsync(User.Identity.Name);

    //get single package 
    Booking booking = _bookingDataService.GetSingle(b => b.BookingID 
               == id);

    if ((booking?.UserID ?? "A") == (user?.Id ?? "B"))
    {
        //create vm
        BookingDetailsViewModel vm = new BookingDetailsViewModel
        {
            BookingDate=booking.BookingDate,
            Price=booking.Price,
            Qty=booking.Qty
        };
        //pass to view
        return View(vm);
        }
        else
        {
            return RedirectToAction("Index", "Customer");
        }
    }
}

【问题讨论】:

  • ?. - ??
  • 不知道什么意思,明明不是你写的……
  • 是的,兄弟。我使用了代码来避免我在操作方法中的问题。运行应用程序时它的工作,但如果在 URL 上输入 ex:Localhost:5000/Booking/Details/5 如果 id 5 不是登录获取异常如何。这就是我使用的原因,我需要了解这到底是什么意思。我不明白为什么这种格式会这样写

标签: c# operators


【解决方案1】:

MyVar?.SomeProperty 检查MyVar 是否为空。

var foo = MyVar?.SomeProperty就像写var foo = ((MyVar == null) ? (null) : (MyVar.SomeProperty))

MyVar.SomeProperty ?? "SomeValue" 检查SomeProperty 是否为空,然后分配值“SomeValue”

var foo = MyVar.SomeProperty ?? "SomeValue"就像写var foo = ((MyVar.SomeProperty == null) ? ("SomeValue") : (MyVar.SomeProperty))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-05
    • 2021-12-25
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多