Phi*_*egg 4 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-功能与-的实体框架式-ASP净MVC应用程序
控制器中有一种让我困惑的方法:
//
// 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));
}
Run Code Online (Sandbox Code Playgroud)
我看到创建了一个名为'saveChangesError'的bool,但在if语句中,有一个方法被调用在名为'GetValueOrDefault()'的布尔值上
在这种情况下究竟发生了什么?我假设GetValueOrDefault()必须是所有布尔类型的方法?我在.NET文档中查看了这个并找到了这个定义:
如果HasValue属性为true,则为Value属性的值; 否则,当前Nullable(Of T)对象的默认值.默认值的类型是当前Nullable(Of T)对象的type参数,默认值的值仅由二进制零组成.
我无法将此定义与.net mvc应用程序上的内容联系起来.
谢谢.
GetValueOrDefault()不是它的一部分bool,它是它的一部分Nullable<T>.这里的关键是bool在函数头中声明的语法:
public ActionResult Delete(int id, bool? saveChangesError)
Run Code Online (Sandbox Code Playgroud)
问号是一个C#语言的结构,它表明这是不是真的一个bool,而是一个Nullable<bool>.值类型,其中bool一个,不能null.但有时如果他们可以的话会很有用.所以Nullable<T>结构存在是为了达到这个目的.
GetValueOrDefault()是该结构上的一个方法,如果没有指定值,它将返回boola bool(或者是false)的默认值.
| 归档时间: |
|
| 查看次数: |
2442 次 |
| 最近记录: |