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

标签 asp.net-mvc asp.net-mvc-3

我正在 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/

相关文章:

javascript - MVC dropdownlist onchange 调用jquery

javascript - 无法使用 jQuery 获取 HTML 表行值

c# - 如何将一个 ViewModel 转换为另一个 ViewModel?

asp.net - 通过长轮询检查数据库的变化

javascript - Ajax 调用返回 viewmodel 但 View 不显示结果

asp.net-mvc - mvc3 maxLength输入

asp.net-mvc-3 - Mini Profiler 不渲染脚本

asp.net-mvc - 获取 VS2010,特别是 Razor View ,将自定义 "data-"属性识别为有效

c# - Autofac - InstancePerHttpRequest 与 InstancePerLifetimeScope

c# - 在 Mvc.Controller 中使用服务器