<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>xiaoma de blog &#187; C#</title>
	<atom:link href="http://www.floatingvectors.com/blog/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.floatingvectors.com/blog</link>
	<description></description>
	<lastBuildDate>Sun, 22 Jan 2012 11:51:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>C# Passing Parameters</title>
		<link>http://www.floatingvectors.com/blog/276/</link>
		<comments>http://www.floatingvectors.com/blog/276/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 12:01:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[软件[Code]]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.floatingvectors.com/blog/?p=276</guid>
		<description><![CDATA[C# Passing Parameters

Passing Value-Type Parameters
A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Therefore, passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no [...]]]></description>
			<content:encoded><![CDATA[<h1>C# Passing Parameters</h1>
<p><strong></strong></p>
<p><strong>Passing Value-Type Parameters</strong></p>
<p>A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Therefore, passing a value-type variable to a method means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the variable. If you want the called method to change the value of the parameter, you have to pass it by reference, using the ref or out keyword.</p>
<p>The following example demonstrates passing value-type parameters by value. The variable n is passed by value to the method SquareIt. Any changes that take place inside the method have no affect on the original value of the variable.</p>
<pre class="brush: c#">

class PassingValByVal
{
    static void SquareIt(int x)
    // The parameter x is passed by value.
    // Changes to x will not affect the original value of x.
    {
        x *= x;
        System.Console.WriteLine(&quot;The value inside the method: {0}&quot;, x);
    }
    static void Main()
    {
        int n = 5;
        System.Console.WriteLine(&quot;The value before calling the method: {0}&quot;, n);

        SquareIt(n);  // Passing the variable by value.
        System.Console.WriteLine(&quot;The value after calling the method: {0}&quot;, n);

        // Keep the console window open in debug mode.
        System.Console.WriteLine(&quot;Press any key to exit.&quot;);
        System.Console.ReadKey();
    }
}
/* Output:
    The value before calling the method: 5
    The value inside the method: 25
    The value after calling the method: 5
*/
</pre>
<p>The variable n, being a value type, contains its data, the value 5. When SquareIt is invoked, the contents of n are copied into the parameter x, which is squared inside the method. In Main, however, the value of n is the same, before and after calling the SquareIt method. In fact, the change that takes place inside the method only affects the local variable x.</p>
<p>The following example is the same as the previous example, except for passing the parameter using the <strong>ref</strong> keyword. The value of the parameter is changed after calling the method.</p>
<pre class="brush: c#">

class PassingValByRef
{
    static void SquareIt(ref int x)
    // The parameter x is passed by reference.
    // Changes to x will affect the original value of x.
    {
        x *= x;
        System.Console.WriteLine(&quot;The value inside the method: {0}&quot;, x);
    }
    static void Main()
    {
        int n = 5;
        System.Console.WriteLine(&quot;The value before calling the method: {0}&quot;, n);

        SquareIt(ref n);  // Passing the variable by reference.
        System.Console.WriteLine(&quot;The value after calling the method: {0}&quot;, n);

        // Keep the console window open in debug mode.
        System.Console.WriteLine(&quot;Press any key to exit.&quot;);
        System.Console.ReadKey();
    }
}
/* Output:
    The value before calling the method: 5
    The value inside the method: 25
    The value after calling the method: 25
*/
</pre>
<p><strong>Passing Reference-Type Parameters</strong></p>
<p>A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref or out keyword.</p>
<p>The following example demonstrates passing a reference-type parameter, arr, by value, to a method, Change. Because the parameter is a reference to arr, it is possible to change the values of the array elements. However, the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable, arr.</p>
<pre class="brush: c#">

class PassingRefByVal
{
    static void Change(int[] pArray)
    {
        pArray[0] = 888;  // This change affects the original element.
        pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
        System.Console.WriteLine(&quot;Inside the method, the first element is: {0}&quot;, pArray[0]);
    }

    static void Main()
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine(&quot;Inside Main, before calling the method, the first element is: {0}&quot;, arr [0]);

        Change(arr);
        System.Console.WriteLine(&quot;Inside Main, after calling the method, the first element is: {0}&quot;, arr [0]);
    }
}
/* Output:
    Inside Main, before calling the method, the first element is: 1
    Inside the method, the first element is: -3
    Inside Main, after calling the method, the first element is: 888
*/
</pre>
<p>In the preceding example, the array, arr, which is a reference type, is passed to the method without the <em>ref</em> parameter. In such a case, a copy of the reference, which points to arr, is passed to the method. The output shows that it is possible for the method to change the contents of an array element, in this case from 1 to 888. However, allocating a new portion of memory by using the new operator inside the Change method makes the variable pArray reference a new array. Thus, any changes after that will not affect the original array, arr, which is created inside Main. In fact, two arrays are created in this example, one inside Main and one inside the Change method.</p>
<p>This example is the same as the previous example, except for using the <strong>ref</strong> keyword in the method header and call. Any changes that take place in the method will affect the original variables in the calling program.</p>
<pre class="brush: c#">

class PassingRefByRef
{
    static void Change(ref int[] pArray)
    {
        // Both of the following changes will affect the original variables:
        pArray[0] = 888;
        pArray = new int[5] {-3, -1, -2, -3, -4};
        System.Console.WriteLine(&quot;Inside the method, the first element is: {0}&quot;, pArray[0]);
    }

    static void Main()
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine(&quot;Inside Main, before calling the method, the first element is: {0}&quot;, arr[0]);

        Change(ref arr);
        System.Console.WriteLine(&quot;Inside Main, after calling the method, the first element is: {0}&quot;, arr[0]);
    }
}
/* Output:
    Inside Main, before calling the method, the first element is: 1
    Inside the method, the first element is: -3
    Inside Main, after calling the method, the first element is: -3
*/
</pre>
<p>All of the changes that take place inside the method affect the original array in Main. In fact, the original array is reallocated using the <strong>new</strong> operator. Thus, after calling the Change method, any reference to arr points to the five-element array, which is created in the Change method.</p>
<p>Swapping strings is a good example of passing reference-type parameters by reference. In the example, two strings, str1 and str2, are initialized in Main and passed to the SwapStrings method as parameters modified by the <strong>ref</strong> keyword. The two strings are swapped inside the method and inside Main as well.</p>
<pre class="brush: c#">

class SwappingStrings
 {
     static void SwapStrings(ref string s1, ref string s2)
     // The string parameter is passed by reference.
     // Any changes on parameters will affect the original variables.
     {
         string temp = s1;
         s1 = s2;
         s2 = temp;
         System.Console.WriteLine(&quot;Inside the method: {0} {1}&quot;, s1, s2);
     }

     static void Main()
     {
         string str1 = &quot;John&quot;;
         string str2 = &quot;Smith&quot;;
         System.Console.WriteLine(&quot;Inside Main, before swapping: {0} {1}&quot;, str1, str2);

         SwapStrings(ref str1, ref str2);   // Passing strings by reference
         System.Console.WriteLine(&quot;Inside Main, after swapping: {0} {1}&quot;, str1, str2);
     }
 }
 /* Output:
     Inside Main, before swapping: John Smith
     Inside the method: Smith John
     Inside Main, after swapping: Smith John
*/
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.floatingvectors.com/blog/276/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Boxing and Unboxing</title>
		<link>http://www.floatingvectors.com/blog/256/</link>
		<comments>http://www.floatingvectors.com/blog/256/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 10:33:26 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[软件[Code]]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.floatingvectors.com/blog/?p=256</guid>
		<description><![CDATA[C# Boxing and Unboxing
 
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.
In [...]]]></description>
			<content:encoded><![CDATA[<h1>C# Boxing and Unboxing</h1>
<p> </p>
<p>Boxing is the process of converting a value type to the type <strong>object</strong> or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.</p>
<p>In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.</p>
<h2>Boxing</h2>
<p>Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type <strong>object</strong> or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.</p>
<p>Consider the following declaration of a value-type variable:</p>
<pre class="brush: c#">

int i=123;
</pre>
<p>The following statement implicitly applies the boxing operation on the variable i:</p>
<pre class="brush: c#">

object o=i;      //Implicit boxing
</pre>
<p>The result of this statement is creating an object reference o, on the stack, that references a value of the type <strong>int</strong>, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.</p>
<p><a href="http://www.floatingvectors.com/blog/wp-content/uploads/2010/01/boxing.png"><img class="aligncenter size-full wp-image-272" title="boxing" src="http://www.floatingvectors.com/blog/wp-content/uploads/2010/01/boxing.png" alt="" width="250" height="170" /></a></p>
<h2>Unboxing</h2>
<p>Unboxing is an explicit conversion from the type <strong>object</strong> to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:</p>
<p>Checking the object instance to make sure that it is a boxed value of the given value type.</p>
<p>Copying the value from the instance into the value-type variable.</p>
<p>The following statements demonstrate both boxing and unboxing operations:</p>
<pre class="brush: c#">

int  i = 123;

object o = i;  //boxing

int j = (int) o;   //unboxing
</pre>
<p>The following figure demonstrates the result of the previous statements.</p>
<p><a href="http://www.floatingvectors.com/blog/wp-content/uploads/2010/01/unboxing.png"><img class="aligncenter size-full wp-image-273" title="unboxing" src="http://www.floatingvectors.com/blog/wp-content/uploads/2010/01/unboxing.png" alt="" width="250" height="219" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.floatingvectors.com/blog/256/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Common Type System</title>
		<link>http://www.floatingvectors.com/blog/249/</link>
		<comments>http://www.floatingvectors.com/blog/249/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 08:26:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[软件[Code]]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.floatingvectors.com/blog/?p=249</guid>
		<description><![CDATA[C# Common Type System
 
The C# typing system contains the following categories:
Value types
Reference types
Pointer types
Variables that are value types store data, and those that are reference types store references to the actual data. Reference types are also referred to as objects. Pointer types can be used only in unsafe mode.
It is possible to convert a value [...]]]></description>
			<content:encoded><![CDATA[<h1>C# Common Type System</h1>
<p> </p>
<p>The C# typing system contains the following categories:</p>
<p>Value types</p>
<p>Reference types</p>
<p>Pointer types</p>
<p>Variables that are value types store data, and those that are reference types store references to the actual data. Reference types are also referred to as objects. Pointer types can be used only in unsafe mode.</p>
<p>It is possible to convert a value type to a reference type, and back again to a value type, by using boxing and unboxing. With the exception of a boxed value type, you cannot convert a reference type to a value type.</p>
<p>Types can derive from other types, called <em>base types</em>. The derived type inherits (with some restrictions) the methods, properties, and other members of the base type. The base type can in turn derive from some other type, in which case the derived type inherits the members of both base types in its inheritance hierarchy. All types, including built-in numeric types such as System.Int32 (C# keyword: int), derive ultimately from a single base type, which is System.Object (C# keyword: object). This unified type hierarchy is called the Common Type System (CTS).</p>
<p>Each type in the CTS is defined as either a <em>value type</em> or a <em>reference type</em>. This includes all custom types in the .NET Framework class library and also your own user-defined types. Types that you define by using the struct keyword are value types; all the built-in numeric types are <strong>structs</strong>. Types that you define by using the class keyword are reference types. Reference types and value types have different compile-time rules, and different run-time behavior.</p>
<p>The following illustration shows the relationship between value types and reference types in the CTS.</p>
<p><a href="http://www.floatingvectors.com/blog/wp-content/uploads/2010/01/csharpCTS.png"></a></p>
<p><strong><a href="http://www.floatingvectors.com/blog/wp-content/uploads/2010/01/csharpCTS.png"><img class="aligncenter size-full wp-image-250" title="csharpCTS" src="http://www.floatingvectors.com/blog/wp-content/uploads/2010/01/csharpCTS.png" alt="" width="514" height="410" /></a></strong></p>
<p><strong>Value Types</strong></p>
<p>Value types derive from System.ValueType, which derives from System.Object. Types that derive from System.ValueType have special behavior in the CLR. Value type variables directly contain their values, which means that the memory is allocated inline in whatever context the variable is declared. There is no separate heap allocation or garbage collection overhead for value-type variables.</p>
<p>There are two categories of value types: struct and enum.</p>
<p>Value types are <em>sealed</em>, which means, for example, that you cannot derive a type from System..::.Int32, and you cannot define a struct to inherit from any user-defined class or struct because a struct can only inherit from System.ValueType. However, a struct can implement one or more interfaces. You can cast a struct type to an interface type; this causes a <em>boxing</em> operation to wrap the struct inside a reference type object on the managed heap. Boxing operations occur when you pass a value type to a method that takes a System.Object as an input parameter.</p>
<p><strong>Reference Types</strong></p>
<p>A type that is defined as a class, delegate, array, or interface is a <em>reference type</em>. At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the object by using the new operator, or assign it an object that has been created elsewhere by using <strong>new.</strong></p>
<p>When the object is created, the memory is allocated on the managed heap, and the variable holds only a reference to the location of the object. Types on the managed heap require overhead both when they are allocated and when they are reclaimed by the automatic memory management functionality of the CLR, which is known as <em>garbage collection</em>. However, garbage collection is also highly optimized, and in most scenarios it does not create a performance issue.<span id="_marker"> </span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.floatingvectors.com/blog/249/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

