Ale*_*nor 17 c# dynamic .net-4.0 asp.net-4.0 viewbag
我有一种情况,我想做一些类似于ASP.NET MVC 3 ViewBag对象的内容,其中属性是在运行时创建的?还是在编译时?
无论如何,我想知道如何用这种行为创建一个对象?
Car*_*ona 23
我创建了这样的东西:
public class MyBag : DynamicObject
{
private readonly Dictionary<string, dynamic> _properties = new Dictionary<string, dynamic>( 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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
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 ) );
Run Code Online (Sandbox Code Playgroud)
请注意,"JAJA"的条目从未创建过......并且仍然不会抛出异常,只返回null
希望这有助于某人
行为方面,ViewBag的行为与ExpandoObject非常相似,因此您可能想要使用它.但是,如果要执行自定义行为,则可以将DynamicObject子类化.使用这些类型的对象时,dynamic关键字非常重要,因为它告诉编译器在运行时而不是编译时绑定方法调用,但是普通的旧clr类型的动态关键字只会避免类型检查而不会给你对象动态实现类型功能,是ExpandoObject或DynamicObject的用途.
ViewBag 声明如下:
dynamic ViewBag = new System.Dynamic.ExpandoObject();
Run Code Online (Sandbox Code Playgroud)