gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 3 - 这个 bool 值在 Controller 中如何工作?

转载 作者:行者123 更新时间:2023-12-01 17:56:09 24 4
gpt4 key购买 nike

我正在 asp 网站上查看 ASP.NET MVC 教程:http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application

Controller 中有一个方法让我感到困惑:

//
// GET: /Student/Delete/5

public ActionResult Delete(int id, bool? saveChangesError)
{
if (saveChangesError.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Unable to save changes. Try again, and if the problem persists contact your system administrator.";
}
return View(db.Students.Find(id));
}

我看到创建了一个名为“saveChangesError”的 bool 值,但在 if 语句中,在该 bool 值上调用了一个名为“GetValueOrDefault()”的方法

这个场景到底发生了什么?我假设 GetValueOrDefault() 必须是所有 bool 类型的方法?我在 .NET 文档中查找了这个定义:

The value of the Value property if the HasValue property is true; otherwise, the default value of the current Nullable(Of T) object. The type of the default value is the type argument of the current Nullable(Of T) object, and the value of the default value consists solely of binary zeroes.

我无法将此定义与 .net mvc 应用程序中发生的情况联系起来。

谢谢。

最佳答案

GetValueOrDefault()不属于 bool , it's part of Nullable<T> 。这里的关键是 bool 的语法。在函数头中声明:

public ActionResult Delete(int id, bool? saveChangesError)

问号是 C# 语言构造,表明这实际上不是 bool ,但是是 Nullable<bool> 。值类型,其中bool是一,不可能 null 。但有时如果他们可以的话会很有用。所以Nullable<T> struct 的存在就是为了达到这个目的。

GetValueOrDefault()是该结构上的一个方法,它将返回 bool 的值或 bool 的默认值( which is false ) 如果未指定值。

关于asp.net-mvc - ASP.NET MVC 3 - 这个 bool 值在 Controller 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9672674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com