创建像 ASP.NET MVC 3 ViewBag 这样的类?
我有一种情况,我想做一些类似于 ASP.NET MVC 3 ViewBag 对象所做的事情,其中属性是在运行时创建的?或者是在编译时?
无论如何,我想知道如何创建具有这种行为的对象?
I have a situation where I would like to do something simular to what was done with the ASP.NET MVC 3 ViewBag object where properties are created at runtime? Or is it at compile time?
Anyway I was wondering how to go about creating an object with this behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我创建了这样的东西:
然后你可以像这样使用它:
注意“JAJA”的条目从未创建......并且仍然不会抛出异常,只是返回 null
希望这对某人有帮助
I created something like this:
then you can use it like this:
note that entry for "JAJA" was never created ... and still doesn't throw an exception, just returns null
hope this helps somebody
从行为角度来看,ViewBag 的行为非常类似于 ExpandoObject,因此也许你想用什么。但是,如果您想执行自定义行为,您可以子类化 DynamicObject。在使用这些类型的对象时,dynamic 关键字很重要,因为它告诉编译器在运行时而不是编译时绑定方法调用,但是普通旧 clr 类型上的动态关键字只会避免类型检查,并且不会为您的对象提供 ExpandoObject 或 DynamicObject 的动态实现类型功能。
Behavior wise the ViewBag acts pretty much like ExpandoObject so that maybe what you want to use. However if you want to do custom behaviors you can subclass DynamicObject. The dynamic keyword is important when using these kinds of objects in that it tells to compiler to bind the method calls at runtime rather than compile time, however the dynamic keyword on a plain old clr type will just avoid type checking and won't give your object dynamic implementation type features that is what ExpandoObject or DynamicObject are for.
使用
动态
类型的对象。 请参阅本文了解详细信息。Use an object of type
dynamic
. See this article for more information.ViewBag
声明如下:ViewBag
is declared like this:我想你想要一个匿名类型。请参阅 http://msdn.microsoft.com/en-us/library/bb397696。 aspx
例如:
然后你就可以像普通 C# 一样获取属性
I think you want an anonymous type. See http://msdn.microsoft.com/en-us/library/bb397696.aspx
For example:
Then you can just get properties as in normal C#