简体   繁体   中英

How object with members that are not specified in class be created?

Picture below shows a MSDN reference of RouteCollectionExtensions.Maproute method.

The method have 1 parameter called defaults which is an object type.

MSDN参考

Picture below shows a line of code (boxed) in a ASP.NET MVC project in Visual Studio which don't contain errors.

在此输入图像描述

The code create a new object and passes it as argument into MapRoute method. The object contains members namely controller , action and id .

However, the object is created from System.Object class. There is no such members specified in the System.Object class.

How the object be created since it do not have the class that have these members?

There are various separate ideas you need to understand here.

Most importantly, there's the idea of an anonymous type . Look at this:

var x = new { Name = "Jon", Location = "Reading" };

That has created an instance of an anonymous type , and assigned the resulting reference to the variable x . At compile-time, the compiler will generate a type that actually has a name, but one you can't refer to.

Now in this case, x will be strongly typed to that "unnamed" type - but it would also be fine to use:

object x = new { Name = "Jon", Location = "Reading" };

After all, we're just creating an object, and every class type is compatible with object , in the same way that we could write:

object x = new StringBuilder();

The example code you've given is very similar, except that it's using the value as an argument to a method call, instead of assigning it to a variable.

The MapRoute method uses reflection to determine the properties of the anonymous type and the values stored in the instance passed in.

The objects created like this;

new { foo="bar", id=7 }

actually have a type, but it's one generated by the compiler. It's called an anonymous type . But it still has properties, and you could still use reflection to see those properties. Eg;

new { foo="bar"}.GetType().GetProperties()

would return an array with one PropertyInfo object in it, representing "foo".

In the MapRoutes method, the parameter is declared as object , but that means it can take anything at all. In this case, it's taking your anonymous object. So MVC uses reflection to tell what properties you've sent to it.

It uses anonymous types, which is supported in c#. The type is created by the compiler later.

See Anonymous Types (C# Programming Guide) from MSDN

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