我的ViewData如何为空,但在调试器中可扩展? [英] How can my ViewData be null, but expandable in the debugger?
问题描述
在调试视图时碰到一个有趣的效果。这个场景很容易复制 - 我在一个 View
中有一个断点,在Watch窗口中我添加了 ViewBag.ViewData
值为 null
。但是,如果我只是添加 ViewBag
并展开对象,我可以看到 ViewData
而不是空
。我也可以成功扩展它并查看其属性。
Just came across an interesting effect while debugging a View. The scenario is easy to reproduce - I have a breakpoint in a View
, in the Watch window I add ViewBag.ViewData
and the value is null
. However, if I just add ViewBag
and expand the object, I can see the ViewData
and it is not null
. I can also successfully expand it and see its properties.
任何人都可以解释这是否是一个错误或是什么原因导致这种行为?
Can anyone explain whether it's a bug or what causes this behavior?
编辑
ViewBag.ViewData
实际上 null
。例如。如果我在View中有这个代码:
ViewBag.ViewData
is actually null
. E.g. if I have this code in the View:
if (ViewBag.ViewData == null)
{
<span>ViewBag.ViewData is null</span>
}
它显示跨度。所以奇怪的是我可以在手表窗口中扩展它,并查看属性。
it displays the span. So the weird part is that I can expand it in the watch window and see the properties.
EDIT2
为了回应@Darin Dimitrov的答案 - 我试图用自定义的测试类重现这个行为,当尝试访问私有的时候我得到一个 RuntimeBinderException
属性:'SomeClass.SomeProperty'由于其保护级别
无法访问:
In response to @Darin Dimitrov's answer - I tried to reproduce this behavior with a custom test class and I get a RuntimeBinderException
when trying to access the private property: 'SomeClass.SomeProperty' is inaccessible due to its protection level
:
public class SomeClass
{
private string SomeProperty;
}
dynamic dynamicObject = new SomeClass();
if (dynamicObject.SomeProperty == null)
{
Console.WriteLine("dynamicObject.SomeProperty is null");
}
在这种情况下,访问<视图中的code> ViewBag.ViewData ( if(ViewBag.ViewData == null)
)的行
In this case, shouldn't I be getting the same exception when accessing ViewBag.ViewData
in the View (the line with if (ViewBag.ViewData == null)
)?
推荐答案
您在调试器/监视窗口中看到的是私人 ViewData $
ViewBag
的c $ c>属性。当您在视图中进行测试时,您显然无法访问此私有字段,并且由于没有相应的公共属性而变为null。
What you see in the debugger/watch window is the private ViewData
property of the ViewBag
. When you do the test in the view you obviously have no access to this private field and you get null because there is no corresponding public property.
现在进行以下测试视图:
Now do the following test in the view:
@if (null == ViewBag
.GetType()
.GetProperty("ViewData", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(ViewBag, null)
)
{
<span>ViewBag.ViewData is null</span>
}
,您将看不到跨度。
当然,这一切非常有趣,但是当涉及到编写真实世界和正确架构的ASP.NET MVC应用程序 ViewData
和 ViewBag
没有地方。这两个是我在ASP.NET MVC应用程序开发中最糟糕的敌人。
Of course all this is very funny but when it comes to writing real world and properly architected ASP.NET MVC applications both ViewData
and ViewBag
have no place. Those two are my worst enemies in ASP.NET MVC application development.
结论:始终使用视图模型和强力类型的视图,并获得乐趣。
Conclusion: always use view models and strongly typed views and have fun.
这篇关于我的ViewData如何为空,但在调试器中可扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!