The package is good, what's in it (transferred from Microsoft)

Source: Internet
Author: User
Tags datetime integer interface modify variables reference wrapper
Microsoft packaging is very good, what is inside?
Author: Eric Gunnerson
Last month, we spent some time learning how to find something related to C #. I received some inquiries about the C # or. NET Web site, so I decided to add a Web site show in my column. Write to Me (ericgu@microsoft.com) your site, each month I will randomly select five sites, at the end of the column listing their URLs.
The end of the opening line.

Types in C #


There are two types in C # and the Common language runtime (CLR): Reference types (in C # with class declarations) and value types (struct declarations in C #). References and value types differ in several important ways. The following table summarizes these differences: reference (Class) value (structure) Retention VariablesReference actual value Activity ValueInline in the heap (in the stack or inline with the object) Default ValueNull 0 = indicatesCopy reference copy Value


The value type "feels" like a data. It includes predefined numeric types and user-defined types, such as ComplexDigital PointOr Rectangle)。 As described above, a variable of a value type is the actual value, so when you use a variable, you typically work with the actual value.
int i = 123;int J = i;i = 55;

After you specify a variable for the second time, two separate variables contain the same value. Modifying the value of I does not change the value of J.
Reference types are used for all objects that cannot be used as value types. A variable of a reference type points to an instance of an object in the heap. This means that when you assign a variable to another variable, only the reference is specified, not the value.
Employee E = new Employee ("Fred"); Employee f = e;f.name = "Barney";

After you specify the variable for the second time, E and F point to the same object. This means that modifying the name of F also changes the name of E, because they refer to the same instance.
This raises a related topic. Some people may have been wondering why System.StringA function in a class does not modify a string, and always returns a new copy of the string. This is because the type of the string is a reference type. If the string is called S.trim ()To modify the internal string, you will encounter the same problem as the Employee (which is very bad for the string).
A member that modifies a class value is called a "change person", and a class that does not have any of the changes is called an immutable class. The existence of immutable classes can make the behavior of a class similar to a value class, but cannot be written as a value class.
If you need to use a variable string class, System.TextTrial in StringBuilder

Turning to simpler models


It is important to use both references and values two types in the language. Value types are lightweight and efficient, and reference types are appropriate for object-oriented development. But now we have two types, and what we need is a simpler model that uses a single type that can encompass all possible values.
Such a common base class can:
    • A virtual function that invokes any value.

    • Writes a collection class that can store any value.

    • Replaces the OLE Automation Variant type.

To achieve this, the common language runtime takes a method of converting a value type to a reference type when it is needed, that is, through a process called wrapping. The wrapped type is a universal base class and can be referenced by various types of objects.

Packaging and lifting packaging


Consider the following code:
int value = 123;object o = value;   wrap int to object int value2 = (int) o; Release packaging to value2

When assigned to O, as part of the assignment, the C # compiler creates enough to hold the heap intReference type wrapper, copy the value to the wrapper, and then mark the wrapper as the actual type (here is System.Int32So that the runtime understands the type of wrapper.
To take a value from the wrapper, you must specify the type of the wrapper (the object can retain any type) by using the force type reload. During execution, the runtime checks whether the type referenced by the object variable is the type specified in the coercion type conversion. If the type is correct, the value is copied back to the value type variable from the wrapper. If the type is incorrect, an exception is caused.
Note that no other conversions will be made during the wrapper, and the type must match exactly. In other words, if we write code:
Long value2 = (long) o; The value of the wrapper is int

Where O is the packaged int, it will cause an exception. However, we can write this:
Long value2 = (long) (int) O;

The conversion will proceed normally.
Although this example demonstrates packaging and unwinding, it may cause some misunderstandings. Writing code to wrap is rare, typically when you pass a variable of a value type to a type object parameter.
Here's a little quiz. I hope you will do it with your heart.

Quiz: How much do you know about packaging?


The following code snippet gives a different scenario. Read the code to determine which piece of code is involved in the wrapper and which paragraph has nothing to do with the wrapper. Some scenarios, such as B, need to be checked for multiple locations.
Scheme 1int total = 35;datetime Date = datetime.now;string s = String.Format (' Your total is {0} on {1} ', total, date);/side Case Bhashtable t = new Hashtable (); T.add (0, "zero"); T.add (1, "one");//scheme cdatetime d = datetime.now; String s = d.tostring ()//Scheme ivint[] A = new int[2];a[0] = 33; Scheme 101ArrayList a = new ArrayList (); A.add (33);//Scheme vimystruct s = new MyStruct; iprocess IP = (iprocess) s;ip. Process ();

Answer


Please check the answer and record the score.

Programme 1


String.Format ()Takes the string as the first argument, and the object as the second and third argument. intAnd DateTimeare value types, they will all be wrapped as a second and third parameter. String.Format ()Use these parameters, and then call the object. ToString ()Converts it to a string representation. If you know intwill be packaged, get a point; DateTimeBe packed, get a point.

Programme B


Hashtable.add ()There are two parameters, one is a keyword and the other is a value. They are all type objects. The value passed to the keyword parameter is an integer, so it must be wrapped to be passed as an object. The value passed to the value parameter is a string (reference type), so the string does not need to be wrapped. Every point of judgment is the right one points.

Programme C


This piece of code is confusing people. One of the purposes of packaging is to implement a virtual function call to a value type parameter. ToString ()is a virtual function of an object, so it looks like it is calling the ToString (), D will be packaged. However, when you convert an object without using D, you do not need to wrap it. The compiler knows that the type is DateTimeVariable can only be of that type (because there is no exported value type, so the variable cannot be an exported type), so it is called directly to the datetime.tostring ()and sets the reference to point to D in the stack. If the answer is correct, get a point.

Programme IV


Arrays in the CLR directly hold their values. For example, a five-element intThe array has enough space to hold 5 int instead of 5 objects. If you think this code has nothing to do with the wrapper, get a point.

Programme 101


Arraylist.add ()Takes an object as an argument, so the integer 33 is wrapped. If the answer is correct, get a point.

Programme VI


Interface is a reference type, you must wrap a value type when casting a value type to an interface implementation. If you know this, get a point.

Final Score


Add all the scores and use the following table to check the understanding of the wrapper: Fractions Description8 on the packaging understand 6-7 understand, but sometimes understand, sometimes confused 3-5 Yes, please continue to 1-2 need to learn 0 not yet getting started

Summary


Finally, summarize the packaging. Wrapping makes it simple and straightforward to write and use functions that have common object parameters. Like many good things, packaging has its downside. Next month, we'll talk about what these bad aspects are, how to reduce the negative impact, and the further explanation of C # (this will make our C # life better).

C # Web Site Highlights


The following Web site was received by me via email, but that's all I know. Don't complain to me if the code there doesn't compile, the computer crashes, or you get into trouble.
There are only two items this month:
    • Http://www.csharphelp.com
    • Http://dotnetwire.com


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.