gpt4 book ai didi

c# - 创建像 ASP.NET MVC 3 ViewBag 这样的类?

转载 作者:IT王子 更新时间:2023-10-29 04:52:23 27 4
gpt4 key购买 nike

我有一种情况,我想做一些类似于在运行时创建属性的 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

希望对大家有帮助

关于c# - 创建像 ASP.NET MVC 3 ViewBag 这样的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5797778/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com