在MVC中,有时根据某些条件设置ViewBag的特定属性。例如:
在我的
if(someCondition)
{
// do some work
ViewBag.SomeProperty = values;
}
return View();
在我的
View
中,我像这样检查属性是否为空:@if(ViewBag.SomeProperty != null)
{
...
}
直到现在我一直认为应该抛出一个异常,因为如果我的条件不满足,那么SomeProperty
就永远不会被设置。这就是为什么我总是使用else
语句将该属性设置为null
。但是我刚刚注意到,即使属性不存在,它也不会抛出异常。例如,在Console Application
中,如果我执行以下操作,我会得到RuntimeBinderException
:
dynamic dynamicVariable = new {Name = "Foo"};
if(dynamicVariable.Surname != null) Console.WriteLine(dynamicVariable.Surname);
但是当涉及到ViewBag
时,这种情况并不会发生。那么这之间有什么区别呢?