Creating a class like ASP.NET MVC 3 ViewBag?

2019-03-23 13:26发布

I have a situation where I would like to do something simular to what was done with the ASP.NET MVC 3 ViewBag object where properties are created at runtime? Or is it at compile time?

Anyway I was wondering how to go about creating an object with this behaviour?

5条回答
▲ chillily
2楼-- · 2019-03-23 13:33

Behavior wise the ViewBag acts pretty much like ExpandoObject so that maybe what you want to use. However if you want to do custom behaviors you can subclass DynamicObject. The dynamic keyword is important when using these kinds of objects in that it tells to compiler to bind the method calls at runtime rather than compile time, however the dynamic keyword on a plain old clr type will just avoid type checking and won't give your object dynamic implementation type features that is what ExpandoObject or DynamicObject are for.

查看更多
贼婆χ
3楼-- · 2019-03-23 13:45

I think you want an anonymous type. See http://msdn.microsoft.com/en-us/library/bb397696.aspx

For example:

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

Then you can just get properties as in normal C#

Console.WriteLine(me.Name + " is a " + me.Occupation);
查看更多
神经病院院长
4楼-- · 2019-03-23 13:47

Use an object of type dynamic. See this article for more information.

查看更多
神经病院院长
5楼-- · 2019-03-23 13:49

ViewBag is declared like this:

dynamic ViewBag = new System.Dynamic.ExpandoObject();
查看更多
ら.Afraid
6楼-- · 2019-03-23 13:59

I created something like this:

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;
    }
}

then you can use it like this:

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 ) );

note that entry for "JAJA" was never created ... and still doesn't throw an exception, just returns null

hope this helps somebody

查看更多
登录 后发表回答