我有一种情况,我想做一些类似于 ASP.NET MVC 3 ViewBag 对象所做的事情,其中属性是在运行时创建的?或者是在编译时?
无论如何,我想知道如何创建具有这种行为的对象?
我创建了这样的东西:
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;
}
}
然后你可以像这样使用它:
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”的条目从未创建...并且仍然不会引发异常,只是返回 null
希望这对某人有帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)