加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC 3 – 这个布尔值如何在控制器中运行

发布时间:2020-12-16 03:58:25 所属栏目:asp.Net 来源:网络整理
导读:我在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 控制器中有一种让我困惑的方法: // // GET: /S
我在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

控制器中有一种让我困惑的方法:

//
        // 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语句中,有一个方法被调用在名为’GetValueOrDefault()’的布尔值上

在这种情况下究竟发生了什么?我假设GetValueOrDefault()必须是所有布尔类型的方法?我在.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为1的值类型不能为null.但有时如果他们可以的话会很有用.所以Nullable< T> struct存在是为了达到这个目的.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读