简体   繁体   中英

What is this thingy called in .net?

I remember a while back, I was working on a web page based on C# razor. There was a response property that served as a kind of pipeline between the controller and the page. I don't know what it was called but it had an interesting property -

basically it works like a dictionary(of string, object) so that you can dump anything in there by any name except you would use it like this:

ThingNameIDontRemember.name = whatever

After adding the stuff I wanted, I think they even showed up in intellisense autocomplete on the other side (unlike what you'd expect from a generic object)

What is that type called and is it also available outside the mvc bundle? I coul'd really use something like that in my current vb.net project.

I think you're looking for the ViewBag .

The ViewBag property enables you to dynamically share values from the controller to the view. It is a dynamic object which means it has no pre-defined properties. You define the properties you want the ViewBag to have by simply adding them to the property. In the view, you retrieve those values by using same name for the property.

More generally, C# 4 introduced dynamic typing using the dynamic type - if an expression is of type dynamic , binding (working out the meaning of names) doesn't happen until execution time. For example:

dynamic d = "foo";
Console.WriteLine(d.Length); // Uses string.Length
d = new int[10];
Console.WriteLine(d.Length); // Uses the array Length
Console.WriteLine(d.Bang()); // Compiles, but will throw at execution time

For a general grab-bag, you can use ExpandoObject :

dynamic expando = new ExpandoObject();
expando.Foo = 10;
expando.Bar = "Some string";
Console.WriteLine(expando.Foo); // 10

There's a lot more to dynamic typing than this, but hopefully that's what you were looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM