【问题标题】:Creating a class like ASP.NET MVC 3 ViewBag?创建一个像 ASP.NET MVC 3 ViewBag 这样的类?
【发布时间】:2011-04-26 23:46:38
【问题描述】:

我有一种情况,我想做一些类似于在运行时创建属性的 ASP.NET MVC 3 ViewBag 对象所做的事情?还是在编译时?

无论如何,我想知道如何创建具有这种行为的对象?

【问题讨论】:

标签: c# dynamic .net-4.0 asp.net-4.0 viewbag


【解决方案1】:

我创造了这样的东西:

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

希望这对某人有所帮助

【讨论】:

    【解决方案2】:

    ViewBag 的行为与ExpandoObject 非常相似,因此可能是您想要使用的。但是,如果您想做自定义行为,您可以继承 DynamicObjectdynamic 关键字在使用这些类型的对象时很重要,因为它告诉编译器在运行时而不是编译时绑定方法调用,但是普通旧 clr 类型上的 dynamic 关键字只会避免类型检查并且不会为您的对象提供动态实现类型的功能,这正是 ExpandoObject 或 DynamicObject 的用途。

    【讨论】:

    • 感谢您指出DynamicObject。这就是我所需要的,现在我意识到 ViewBag '附加'到 ViewData 因为 DynamicViewDataDictionary
    【解决方案3】:

    使用dynamic 类型的对象。 See this article 了解更多信息。

    【讨论】:

      【解决方案4】:

      ViewBag 声明如下:

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

      【讨论】:

        【解决方案5】:

        我想你想要一个匿名类型。见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);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-03
          • 1970-01-01
          相关资源
          最近更新 更多