简体   繁体   中英

VB.NET/ASP.NET With and New keyword muddle

Can someone explain how New works with the With keyword in this example from the MVC framework.

routes.MapRoute("Default", 
                "{controller}/{action}/{id}", 
                New With {.controller = "Home", .action = "Index", .id = ""})

This syntax is used to create an anonymous type in VB.Net.

It allows you to define a type on the fly with a set of name / value pairs. The names all turn into properties on the type. If you open up the generated assembly in reflector you will be able to see these types.

Don't let the With syntax portion fool you. This feature has nothing to do with the "With" context feature of VB.Net. Other than the "." prefix on the value names.

It creates a new anonymous class with the specified properties.

More information from MSDN .

Here "new" is declaring an anonymous class.

This class has no formal definition (ie no "Public Class " definition), it's structure is defined by the items in the curly's after the with. So it defines and constructs a class in a single statement.

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