创建类似ASP.NET MVC 3 ViewBag的类?

我有一种情况,我希望做一些与ASP.NET MVC 3 ViewBag对象(在运行时创建属性)所做的事情相似的事情? 还是在编译时?

无论如何,我想知道如何用这种行为创建一个对象?

使用dynamic类型的对象。 有关更多信息, 请参阅此文章 。

我创建了这样的东西:

 public class MyBag : DynamicObject { private readonly Dictionary _properties = new Dictionary( StringComparer.InvariantCultureIgnoreCase ); public override bool TryGetMember( GetMemberBinder binder, out dynamic result ) { result = this._properties.ContainsKey( binder.Name ) ? this._properties[ binder.Name ] : null; return true; } public override bool TrySetMember( SetMemberBinder binder, dynamic value ) { if( value == null ) { if( _properties.ContainsKey( binder.Name ) ) _properties.Remove( binder.Name ); } else _properties[ binder.Name ] = value; return true; } } 

然后你可以像这样使用它:

 dynamic bag = new MyBag(); bag.Apples = 4; bag.ApplesBrand = "some brand"; MessageBox.Show( string.Format( "Apples: {0}, Brand: {1}, Non-Existing-Key: {2}", bag.Apples, bag.ApplesBrand, bag.JAJA ) ); 

请注意,“JAJA”的条目从未创建过……并且仍然不会抛出exception,只返回null

希望这有助于某人

行为方面,ViewBag的行为与ExpandoObject非常相似,因此您可能想要使用它。 但是,如果要执行自定义行为,则可以inheritanceDynamicObject 。 当使用这些类型的对象时, 动态关键字非常重要,因为它告诉编译器在运行时而不是编译时绑定方法调用,但是普通的旧clr类型的动态关键字只会避免类型检查而不会给你对象动态实现类型function是ExpandoObject或DynamicObject的用途。

ViewBag声明如下:

 dynamic ViewBag = new System.Dynamic.ExpandoObject(); 

我想你想要一个匿名类型。 请参阅http://msdn.microsoft.com/en-us/library/bb397696.aspx

例如:

 var me = new { Name = "Richard", Occupation = "White hacker" }; 

那么你可以像普通的C#一样获得属性

 Console.WriteLine(me.Name + " is a " + me.Occupation);