"Anonymous" Object Type

Source: Internet
Author: User
Tags define local reflector
1.3.3 "anonymous" Object Type Jin xuliang Electronics Industry Press I want to comment (0) font size: T | T

Overall rating:

I want to read (0) I want to read (0) I have read (8) I want to read (3) I have 8 people who have published book reviews

《. Net4.0 Object-Oriented Programming (basic) Chapter 1st. NET Object-Oriented Programming basics, this chapter mainly introduces to readers. net basic knowledge of object-oriented programming, the first two sections. what is net and how is it based on.. NET platform to develop applications ,. net program running mechanism and other content, its purpose is to help readers form a pair. NET platform. This section describes the object types of "anonymous.

AD:


    1.3.3 "anonymous" Object Type

    In C #3.0 and later versions, we can use the VaR keyword to define a strange "No type" variable (called "implicit type local variable "):

     
     
    1. VaR sums = 100;
    2. Console. writeline (sum * 2); // output: 200

    It seems that CLR can intelligently infer that sum is an int type variable.

    In fact, the C # compiler rather than the CLR completes the type inference work. The C # compiler infers that sum is an int Type Variable Based on the assigned value "100, it directly generates the Il code that assigns the constant "100" to it. CLR only executes it mechanically.

    When using VAR to define Partial Variables of the implicit type, the compiler must be able to deduce the variable type. Otherwise, compilation fails.

    VaR can only be used to define local variables within a method, and cannot be defined as a field of a class. For example, the following code cannot be compiled:

     
     
    1. class A  
    2. {  
    3. var Value=100;  

    The VaR keyword is introduced here because we can use it to create an object without defining a class.

    See the following code (useanonymoustype ):

     
     
    1. var v = new { Amount = 108, Message = "Hello" }; 

    The code above creates an anonymous object v with two fields: Amount and message.

    There is no difference between the usage of an anonymous object and a common object:

     
     
    1. Console.WriteLine("Amount:{0}, Message:{1}", v.Amount, v.Message); 

    The output result of the above Code is:

     
     
    1. Amount:108, Message:Hello 

    Wait a moment. This example seems to be against the basic principles of object-oriented programming. How can we create objects without defining classes?

    In fact, everything is the magic behind the C # compiler.

    Use the ildasmtool to compile the collection (useanonymoustype.exe) generated by the sample program. You can see that a type with a very strange name is generated (see Figure 1-13 ).

     
    Figure 1-13 C # "anonymous type" generated by the compiler for anonymous objects"

    Open the Il code corresponding to the main method, and everything is clear.

    Originally, the C # compiler dynamically created a type (its name is 1 13). Its constructor includes the amount and message parameters. The variable V in the main method is set to a local variable of this type.

    The main method first uses "108" and "hello" as real parameters to call this type of constructor to create an object, and then let variable v reference this created object.

    Read the value of amount and message in the two fields of the V object by directly calling the get_amount method and get_message method defined by the anonymous type.

    Therefore, the anonymous Type feature of C # does not violate the object-oriented programming principle of "defining classes before creating objects.

    What is interesting about anonymous objects is that we can write such code:

     
     
    1. var v = new { Amount = 108, Message = "Hello" };  
    2. Console.WriteLine(v); 

    The above code output:

     
     
    1. { Amount = 108, Message = Hello } 

    The result of this operation raises a series of problems:

    1) Where does the output result come from?

    2) How can console. writeline directly receive a temporary anonymous object v? How does it know how many fields this object has?

    If you have basic object-oriented knowledge and use the ildasm and reflector tools, it is not difficult to explain this phenomenon.

    First, we can know from the Il code generated by the main method that "console. writeline (V);" actually calls the following overload form of the console. writeline method:

     
     
    1. public static void WriteLine(object value); 

    Now you can use the reflector tool to view the implementation code of the console. writeline (object) method. You will find that the above method internally calls the tostring method of the parameter value to generate a string and then output the string.

    Now return to ildasm, find the tostring method in the anonymous type generated by the C # compiler, open it, and check the Il code in it to see why the example will get that result, this job is left to the reader as an exercise.

    The last two questions are related to why C # introduces such "hidden" syntax features:

    1) Why do we need to use the implicit type to define variables instead of directly specifying the data type?

    2) What is the actual purpose of an anonymous object?

    The answer is:

    Implicit type variables and anonymous types are mainly used in LINQ.

    See the following LINQ to SQL code:

     
     
    1. // Extract product information from the SQL Server database
    2. VaR productquery =
    3.  
    4. From prod in products
    5. Select New {prod. Color, prod. Price };
    6. // Display the found Product Information
    7. Foreach (var v in productquery)
    8. Console. writeline ("color = {0}, price = {1}", V. Color, V. Price );

    The code above uses an anonymous object to generate database query results. The actual type of the local variable productquery of the implicit type is "ienumerable <custom anonymous type automatically generated by the compiler>". If the implicit type variable and anonymous type attribute of C # are not used, writing code with the same function can be tricky-because you must now "explicitly" define a type that encapsulates the query results (color and price.

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.