mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 2 doc

82 502 0
mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 2 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

50 Chapter Framework Fundamentals Modify the Main method to create a Manager object instead of a Person object and pass a phone number and location into the constructor Then run your application to verify that it works correctly Exercise 2: Respond to an Event In this exercise, you create a class that responds to a timer event Using Visual Studio, create a new Windows Forms Application project Name the project TimerEvents Add a ProgressBar control to the form, as shown in Figure 1-2 Figure 1-2 You will control this progress bar by responding to timer events Within the form class declaration, declare an instance of a System.Windows Forms.Timer object Timer objects can be used to throw events after a specified number of milliseconds The following code sample shows how to declare a Timer object: ' VB Dim t As System.Windows.Forms.Timer // C# System.Windows.Forms.Timer t; In the designer, view the properties for the form Then view the list of events Double-click the Load event to automatically create an event handler that runs the first time the form is initialized Within the method, initialize the Timer object, set the interval to second, create an event handler for the Tick event, and start the timer The following code sample demonstrates this: ' VB Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Shown t = New System.Windows.Forms.Timer t.Interval = 1000 AddHandler t.Tick, AddressOf Me.t_Tick t.Start() End Sub Lesson 3: Constructing Classes 51 // C# private void Form1_Load(object sender, EventArgs e) { t = new System.Windows.Forms.Timer(); t.Interval = 1000; t.Tick += new EventHandler(t_Tick); t.Start(); } Implement the method that responds to the Timer.Tick event When the event occurs, add 10 to the ProgressBar.Value property Then stop the timer if the ProgressBar.Value property has reached 100 The following code sample demonstrates this: ' VB Private Sub t_Tick(ByVal sender As Object, ByVal e As EventArgs) ProgressBar1.Value += 10 If ProgressBar1.Value >= 100 Then t.Stop() End If End Sub // C# void t_Tick(object sender, EventArgs e) { progressBar1.Value += 10; if (progressBar1.Value >= 100) t.Stop(); } Run the application to verify that it responds to the Timer event every second Lesson Summary Use inheritance to create new types based on existing ones Use interfaces to define a common set of members that must be implemented by related types Partial classes split a class definition across multiple source files Events allow you to run a specified method when something occurs in a different section of code Use attributes to describe assemblies, types, and members Use the TypeForwardedTo attribute to move a type from one class library to another 52 Chapter Framework Fundamentals Lesson Review You can use the following questions to test your knowledge of the information in Lesson 3, “Constructing Classes.” The questions are also available on the companion CD if you prefer to review them in electronic form NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book Which of the following statements are true? (Choose all that apply.) A Inheritance defines a contract between types B Interfaces define a contract between types C Inheritance derives a type from a base type D Interfaces derive a type from a base type Which of the following are examples of built-in generic types? (Choose all that apply.) A Nullable B Boolean C EventHandler D System.Drawing.Point You create a generic class in which you store field members whose type is generic What you to dispose of the objects stored in the fields? A Call the Object.Dispose method B Implement the IDisposable interface C Derive the generic class from the IDisposable class D Use constraints to require the generic type to implement the IDisposable interface You’ve implemented an event delegate from a class, but when you try to attach an event procedure you get a compiler error that there is no overload that matches the delegate What happened? A The signature of the event procedure doesn’t match that defined by the delegate B The event procedure is declared Shared/static, but it should be an instance member instead Lesson 3: Constructing Classes 53 C You mistyped the event procedure name when attaching it to the delegate D The class was created in a different language You are creating a class that needs to be sorted when in a collection Which interface should you implement? A IEquatable B IFormattable C IDisposable D IComparable 54 Chapter Framework Fundamentals Lesson 4: Converting Between Types Often, you need to convert between two different types For example, you might need to determine whether an int is greater or less than a double, pass a double to a method that requires an int as a parameter, or display a number as text This lesson describes how to convert between types in both Visual Basic and C# Type conversion is one of the few areas where Visual Basic and C# differ considerably After this lesson, you will be able to: Convert between types Explain boxing and why it should be avoided Implement conversion operators Estimated lesson time: 20 minutes Conversion in Visual Basic and C# By default, Visual Basic allows implicit conversions between types, while C# prohibits implicit conversions that lose precision To turn off implicit conversions in Visual Basic, add Option Strict On to the top of each code file, or (in Visual Studio) select Project, choose Properties, select Compile, and select Option Strict On for the entire project Both Visual Basic and C# allow implicit conversion if the destination type can accommodate all possible values from the source type That is called a widening conversion, and it is illustrated by the following example: ' VB Dim i As Integer = Dim d As Double = 1.0001 d = i ' Conversion allowed // C# int i = 1; double d = 1.0001; d = i; // Conversion allowed If the range or precision of the source type exceeds that of the destination type, the operation is called a narrowing conversion, which usually requires explicit conversion Table 1-7 lists the ways to perform explicit conversions Lesson 4: Converting Between Types Table 1-7 55 Methods for Explicit Conversion System Type Visual Basic C# System.Convert Converts Between types that implement the System.IConvertible interface CType (type) cast operator Between types that define conversion operators type.ToString, type.Parse Between string and base types; throws an exception if the conversion is not possible type.TryParse, type.TryParseExact From string to a base type; returns false if the conversion is not possible CBool, CInt, CStr, etc Between base Visual Basic types; compiled inline for better performance (Visual Basic only.) DirectCast, TryCast Between types DirectCast throws an exception if the types are not related through inheritance or if they not share a common interface; TryCast returns Nothing in those situations (Visual Basic only.) Narrowing conversions may return an incorrect result if the source value exceeds the destination type’s range If a conversion between the types is not defined, you receive a compile-time error 56 Chapter Framework Fundamentals What Are Boxing and Unboxing? Boxing converts a value type to a reference type, and unboxing converts a reference type to a value type The following example demonstrates boxing by converting an int (a value type) to an object (a reference type): ' VB Dim i As Integer = 123 Dim o As Object = CType(i, Object) // C# int i = 123; object o = (object)i; Unboxing occurs if you assign a reference object to a value type variable The following example demonstrates unboxing: ' VB Dim o As Object = 123 Dim i As Integer = CType(o, Integer) // C# object o = 123; int i = (int)o; Boxing Tips Boxing and unboxing incur overhead, so you should avoid them when programming intensely repetitive tasks Boxing also occurs when you call virtual methods that a structure or any value type inherits from System.Object, such as ToString Follow these tips to avoid unnecessary boxing: Implement type-specific versions (overloads) for a procedure that must be able to accept various value types It is better to create several overloaded procedures than one procedure that accepts an Object argument Use generics whenever possible instead of coding arguments of the object type Override the ToString, Equals, and GetHash virtual members when defining structures How to Implement Conversion in Custom Types You can define conversions for your own types in several ways Which technique you choose depends on the type of conversion you want to perform, as follows: Define conversion operators to simplify narrowing and widening conversions between numeric types Lesson 4: Converting Between Types 57 Override ToString to provide conversion to strings, and override Parse to provide conversion from strings Implement System.IConvertible to enable conversion through System.Convert Use this technique to enable culture-specific conversions Implement a TypeConverter class to enable design-time conversion for use in the Properties window of Visual Studio Design-time conversion is outside the scope of the exam, and the TypeConverter class is not covered in this book MORE INFO Design-Time Conversion For more information about design-time conversion, read “Extending Design-Time Support” at http://msdn.microsoft.com/en-us/library/37899azc.aspx Defining conversion operators allows you to assign from a value type directly to your custom type Use the Widening/implicit keyword for conversions that don’t lose precision; use the Narrowing/explicit keyword for conversions that could lose precision For example, the following structure defines operators that allow assignment to and from integer values (note the bold keywords): ' VB Structure TypeA Public Value As Integer ' Allows implicit conversion from an integer Public Shared Widening Operator CType(ByVal arg As Integer) As TypeA Dim res As New TypeA res.Value = arg Return res End Operator ' Allows explicit conversion to an integer Public Shared Narrowing Operator CType(ByVal arg As TypeA) As Integer Return arg.Value End Operator ' Provides string conversion (avoids boxing) Public Overrides Function ToString() As String Return Me.Value.ToString End Function End Structure // C# struct TypeA { public int Value; 58 Chapter Framework Fundamentals // Allows implicit conversion from an integer public static implicit operator TypeA(int arg) { TypeA res = new TypeA(); res.Value = arg; return res; } // Allows explicit conversion to an integer public static explicit operator int(TypeA arg) { return arg.Value; } // Provides string conversion (avoids boxing) public override string ToString() { return this.Value.ToString(); } } The preceding type also overrides ToString to perform the string conversion without boxing Now you can assign integers to a variable of this type directly, as shown here: ' VB Dim a As TypeA, i As Integer ' Widening conversion is OK implicit a = 42 ' Rather than a.Value = 42 ' Narrowing conversion in VB does not need to be explicit i = a ' Narrowing conversion can be explicit i = CInt(a) ' Rather than i = a.Value ' This syntax is OK, too i = CType(a, Integer) Console.WriteLine("a = {0}, i = {1}", a.ToString, i.ToString) // C# TypeA a; int i; // Widening conversion is OK implicit a = 42; // Rather than a.Value = 42 // Narrowing conversion must be explicit in C# i = (int)a; // Rather than i = a.Value Console.WriteLine("a = {0}, i = {1}", a.ToString(), i.ToString()); To implement the System.IConvertible interface, add the IConvertible interface to the type definition Then use Visual Studio to implement the interface automatically Visual Studio inserts member declarations for 17 methods, including GetTypeCode, ChangeType, and ToType methods for each base type You don’t have to implement every method, and some—such as ToDateTime—probably are invalid For invalid methods, simply throw an exception—in C#, Visual Studio automatically adds code to throw an exception for any conversion methods you don’t implement Lesson 4: Converting Between Types 59 After you implement IConvertible, the custom type can be converted using the standard System.Convert class, as shown here: ' VB Dim a As TypeA, b As Boolean a = 42 ' Convert using ToBoolean b = Convert.ToBoolean(a) Console.WriteLine("a = {0}, b = {1}", a.ToString, b.ToString) // C# TypeA a; bool b; a = 42; // Convert using ToBoolean b = Convert.ToBoolean(a); Console.WriteLine("a = {0}, b = {1}", a.ToString(), b.ToString()); If you not implement a conversion, throw an InvalidCastException Lab: Safely Performing Conversions The following exercises show how to avoid problems with implicit conversions so that your programs function predictably Navigate to the \\Chapter01\ Lesson1\Exercise1\Partial folder Exercise 1: Examine Implicit Conversion In this exercise, you examine conversion to determine which number types allow implicit conversion Create a new Console Application project in Visual Studio Declare instances of three value types: Int16, Int32, and double The following code sample demonstrates this: ' VB Dim i16 As Int16 = Dim i32 As Int32 = Dim db As Double = // C# Int16 i16 = 1; Int32 i32 = 1; double db = 1; Attempt to assign each variable to all the others, as the following code sample demonstrates: ' VB i16 = i32 i16 = db Lesson 1: Forming Regular Expressions 117 Matches either a space (\s) or a hyphen (\-) separating the area code from the rest of the phone number The question mark that follows the brackets makes the space or hyphen optional [\s\-]? Matches exactly three numeric digits \d{3} Optionally matches a hyphen \-? \d{4}$ Requires that the string end with four numeric digits Using one line of code, complete the IsZip method so that it returns true if the parameter matches any of the following formats: 01111 01111-1111 Although many different regular expressions would work, the IsZip method you write could look like this: ' VB Function IsZip(ByVal s As String) As Boolean Return Regex.IsMatch(s, "^\d{5}(\-\d{4})?$") End Function // C# static bool IsZip(string s) { return Regex.IsMatch(s, @"^\d{5}(\-\d{4})?$"); } Each component of this regular expression matches a required or optional part of a ZIP code: ^ Matches the beginning of the string \d{5} Matches exactly five numeric digits Optionally matches a hyphen followed by exactly four numeric digits Because the expression is surrounded by parentheses and followed by a question mark, the expression is considered optional (\-\d{4})? $ Matches the end of the string Build and run the project The output should match the following: (555)555-1212 is a phone number (555) 555-1212 is a phone number 555-555-1212 is a phone number 5555551212 is a phone number 01111 is a zip code 118 Chapter Searching, Modifying, and Encoding Text 01111-1111 is a zip code 47 is unknown 111-11-1111 is unknown If the output you get does not match the output just shown, adjust your regular expressions as needed Exercise 2: Reformat a String In this exercise, you must reformat phone numbers into a standard (###) ###-#### format Open the project that you created in Exercise Add a method named ReformatPhone that returns a string and accepts a single string as an argument Using regular expressions, accept phone-number data provided in one of the formats used in Exercise 1, and reformat the data into the (###) ###-#### format Although many different regular expressions would work, the ReformatPhone method you write could look like this: ' VB Function ReformatPhone(ByVal s As String) As String Dim m As Match = Regex.Match(s, _ "^\(?(\d{3})\)?[\s\-]?(\d{3})\-?(\d{4})$") Return String.Format("({0}) {1}-{2}", _ m.Groups(1), m.Groups(2), m.Groups(3)) End Function // C# static string ReformatPhone(string s) { Match m = Regex.Match(s, @"^\(?(\d{3})\)?[\s\-]?(\d{3})\-?(\d{4})$"); return String.Format("({0}) {1}-{2}", m.Groups[1], m.Groups[2], m.Groups[3]); } Notice that this regular expression almost exactly matches that used in the IsPhone method The only difference is that each of the \d{n} expressions is surrounded by parentheses This places each of the sets of numbers into a separate group that can be easily formatted using String.Format Change the Main method so that it writes ReformatPhone(s) in the foreach loop instead of simply writing s The foreach loop should now look like this (the changes are shown in bold): ' VB For Each s As String In input If IsPhone(s) Then Lesson 1: Forming Regular Expressions 119 Console.WriteLine(ReformatPhone(s) + " is a phone number") Else If IsZip(s) Then Console.WriteLine(s + " is a zip code") Else Console.WriteLine(s + " is unknown") End If End If Next // C# foreach (string s in input) { if (IsPhone(s)) Console.WriteLine(ReformatPhone(s) + " is a phone number"); else if (IsZip(s)) Console.WriteLine(s + " is a zip code"); else Console.WriteLine(s + " is unknown"); } Build and run the project The output should match the following: (555) 555-1212 is a phone (555) 555-1212 is a phone (555) 555-1212 is a phone (555) 555-1212 is a phone 01111 is a zip code 01111-1111 is a zip code 47 is unknown 111-11-1111 is unknown number number number number Notice that each of the phone numbers has been reformatted even though they were initially in four different formats If your output does not match the output just shown, adjust your regular expressions as needed Lesson Summary Regular expressions enable you to determine whether text matches almost any type of format Regular expressions support dozens of special characters and operators The most commonly used are ^ to match the beginning of a string, $ to match the end of a string, ? to make a character optional, to match any character, and * to match zero or more characters To extract data using a regular expression, create a pattern using groups to specify the data you need to extract, call Regex.Match to create a Match object, and then examine each of the items in the Match.Groups array To reformat text data using a regular expression, call the static Regex.Replace method 120 Chapter Searching, Modifying, and Encoding Text Lesson Review You can use the following questions to test your knowledge of the information in Lesson 1, “Forming Regular Expressions.” The questions are also available on the companion CD if you prefer to review them in electronic form NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book You are writing an application to update absolute hyperlinks in HTML files You have loaded the HTML file into a string named s Which of the following code samples best replaces http:// with https://, regardless of whether the user types the URL in uppercase or lowercase? A ' VB s = Regex.Replace(s, "http://", "https://") // C# s = Regex.Replace(s, "http://", "https://"); B ' VB s = Regex.Replace(s, "https://", "http://") // C# s = Regex.Replace(s, "https://", "http://"); C ' VB s = Regex.Replace(s, "http://", "https://", RegexOptions.IgnoreCase) // C# s = Regex.Replace(s, "http://", "https://", RegexOptions.IgnoreCase); D ' VB s = Regex.Replace(s, "https://", "http://", RegexOptions.IgnoreCase) // C# s = Regex.Replace(s, "https://", "http://", RegexOptions.IgnoreCase); You are writing an application to process data contained in a text form Each file contains information about a single customer The following is a sample form: First Name: Tom Last Name: Perham Lesson 1: Forming Regular Expressions 121 Address: 123 Pine St City: Springfield State: MA Zip: 01332 You have read the form data into the String variable s Which of the following code samples correctly stores the data portion of the form in the fullName, address, city, state, and zip variables? A ' VB Dim p As String = "First Name: (?.*$)\n" + _ "Last Name: (?.*$)\n" + _ "Address: (?.*$)\n" + _ "City: (?.*$)\n" + _ "State: (?.*$)\n" + _ "Zip: (?.*$)" Dim m As Match = Regex.Match(s, p, RegexOptions.Multiline) Dim fullName As String = m.Groups("firstName").ToString + " " + _ m.Groups("lastName").ToString Dim address As String = m.Groups("address").ToString Dim city As String = m.Groups("city").ToString Dim state As String = m.Groups("state").ToString Dim zip As String = m.Groups("zip").ToString // C# string p = @"First Name: (?.*$)\n" + @"Last Name: (?.*$)\n" + @"Address: (?.*$)\n" + @"City: (?.*$)\n" + @"State: (?.*$)\n" + @"Zip: (?.*$)"; Match m = Regex.Match(s, p, RegexOptions.Multiline); string fullName = m.Groups["firstName"] + " " + m.Groups["lastName"]; string address = m.Groups["address"].ToString(); string city = m.Groups["city"].ToString(); string state = m.Groups["state"].ToString(); string zip = m.Groups["zip"].ToString(); B Dim p As String = "First Name: (?.*$)\n" + _ "Last Name: (?.*$)\n" + _ "Address: (?.*$)\n" + _ "City: (?.*$)\n" + _ "State: (?.*$)\n" + _ "Zip: (?.*$)" Dim m As Match = Regex.Match(s, p) Dim fullName As String = m.Groups("firstName").ToString + " " + _ m.Groups("lastName").ToString Dim address As String = m.Groups("address").ToString Dim city As String = m.Groups("city").ToString Dim state As String = m.Groups("state").ToString Dim zip As String = m.Groups("zip").ToString 122 Chapter Searching, Modifying, and Encoding Text // C# string p = @"First Name: (?.*$)\n" + @"Last Name: (?.*$)\n" + @"Address: (?.*$)\n" + @"City: (?.*$)\n" + @"State: (?.*$)\n" + @"Zip: (?.*$)"; Match m = Regex.Match(s, p); string fullName = m.Groups["firstName"] + " " + m.Groups["lastName"]; string address = m.Groups["address"].ToString(); string city = m.Groups["city"].ToString(); string state = m.Groups["state"].ToString(); string zip = m.Groups["zip"].ToString(); C Dim p As String = "First Name: (?.*$)\n" + _ "Last Name: (?.*$)\n" + _ "Address: (?.*$)\n" + _ "City: (?.*$)\n" + _ "State: (?.*$)\n" + _ "Zip: (?.*$)" Dim m As Match = Regex.Match(s, p, RegexOptions.Multiline) Dim fullName As String = m.Groups("").ToString + " " + _ m.Groups("").ToString Dim address As String = m.Groups("").ToString Dim city As String = m.Groups("").ToString Dim state As String = m.Groups("").ToString Dim zip As String = m.Groups("").ToString // C# string p = @"First Name: (?.*$)\n" + @"Last Name: (?.*$)\n" + @"Address: (?.*$)\n" + @"City: (?.*$)\n" + @"State: (?.*$)\n" + @"Zip: (?.*$)"; Match m = Regex.Match(s, p, RegexOptions.Multiline); string fullName = m.Groups[""] + " " + m.Groups[""]; string address = m.Groups[""].ToString(); string city = m.Groups[""].ToString(); string state = m.Groups[""].ToString(); string zip = m.Groups[""].ToString(); D Dim p As String = "First Name: (?.*$)\n" + _ "Last Name: (?.*$)\n" + _ "Address: (?.*$)\n" + _ "City: (?.*$)\n" + _ "State: (?.*$)\n" + _ "Zip: (?.*$)" Dim m As Match = Regex.Match(s, p) Dim fullName As String = m.Groups("").ToString + " " + _ m.Groups("").ToString Lesson 1: Forming Regular Expressions Dim Dim Dim Dim 123 address As String = m.Groups("").ToString city As String = m.Groups("").ToString state As String = m.Groups("").ToString zip As String = m.Groups("").ToString // C# string p = @"First Name: (?.*$)\n" + @"Last Name: (?.*$)\n" + @"Address: (?.*$)\n" + @"City: (?.*$)\n" + @"State: (?.*$)\n" + @"Zip: (?.*$)"; Match m = Regex.Match(s, p); string fullName = m.Groups[""] + " " + m.Groups[""]; string address = m.Groups[""].ToString(); string city = m.Groups[""].ToString(); string state = m.Groups[""].ToString(); string zip = m.Groups[""].ToString(); Which of the following regular expressions matches the strings zoot and zot? A z(oo)+t B zo*t$ C $zo*t D ^(zo)+t Which of the following strings match the regular expression ^a(mo)+t.*z$? (Choose all that apply.) A amotz B amomtrewz C amotmoz D atrewz E amomomottothez 124 Chapter Searching, Modifying, and Encoding Text Lesson 2: Encoding and Decoding Every string and text file is encoded using one of many different encoding standards Most of the time, the NET Framework handles the encoding for you automatically However, there are times when you might need to control encoding and decoding manually, such as during the following procedures: Interoperating with legacy or UNIX systems Reading or writing text files in other languages Creating HTML pages Generating e-mail messages This lesson describes common encoding techniques and shows you how to use them in NET Framework applications After this lesson, you will be able to: Describe the importance of encoding and list common encoding standards Use the Encoding class to specify encoding formats and convert between encoding standards Programmatically determine which code pages the NET Framework supports Create files using a specific encoding format Read files using unusual encoding formats Estimated lesson time: 30 minutes Understanding Encoding Although it was not the first encoding type, American Standard Code for Information Interchange (ASCII) is still the foundation for existing encoding types ASCII assigned characters to 7-bit bytes using the numbers through 127 These characters included English uppercase and lowercase letters, numbers, punctuation, and some special control characters For example, 0x21 is !, 0x31 is 1, 0x43 is C, 0x63 is c, and 0x7D is } While ASCII was sufficient for most English-language communications, ASCII did not include characters used in non-English alphabets To enable computers to be used in non-English-speaking locations, computer manufacturers used the remaining values—128 through 255—in an 8-bit byte Over time, different locations assigned unique characters to values greater than 127 Because different locations might have different characters assigned to a single value, transferring documents between different languages created problems Lesson 2: Encoding and Decoding 125 To help reduce these problems, the American National Standards Institute (ANSI) defined code pages that had standard ASCII characters for through 127 and languagespecific characters for 128 through 255 A code page is a list of selected character codes (characters represented as code points) in a certain order Code pages are usually defined to support specific languages or groups of languages that share common writing systems Windows code pages contain 256 code points and are zero-based If you’ve ever received an e-mail message or seen a Web page that seemed to have box characters or question marks where letters should appear, you have seen an encoding problem Because people create Web pages and e-mails in many different languages, each must be tagged with an encoding type For example, an e-mail might include one of the following headers: Content-Type: text/plain; charset=ISO-8859-1 Content-Type: text/plain; charset="Windows-1251" ISO-8859-1 corresponds to code page 28591, Western European (ISO) If it had specified ISO-8859-7, it could have contained characters from the Greek (ISO) code page, number 28597 Similarly, HTML Web pages typically include a meta tag such as one of the following: More and more, ASCII and ISO 8859 encoding types are being replaced by Unicode Unicode is a massive code page with tens of thousands of characters that support most languages and scripts, including Latin, Greek, Cyrillic, Hebrew, Arabic, Chinese, and Japanese Unicode itself does not specify an encoding type; however, there are several standards for encoding Unicode The NET Framework uses Unicode UTF-16 (Unicode Transformation Format, 16-bit encoding form) to represent characters In some cases, the NET Framework uses UTF-8 internally The System.Text namespace provides classes that allow you to encode and decode characters System.Text encoding support includes the following encodings: Unicode UTF-32 encoding represents Unicode characters as sequences of 32-bit integers You can use the UTF32Encoding class to convert characters to and from UTF-32 encoding Unicode UTF-32 encoding Unicode UTF-16 encoding represents Unicode characters as sequences of 16-bit integers You can use the UnicodeEncoding class to convert characters to and from UTF-16 encoding Unicode UTF-16 encoding 126 Chapter Searching, Modifying, and Encoding Text Unicode UTF-8 uses 8-bit, 16-bit, 24-bit, and up to 48-bit encoding Values through 127 use 8-bit encoding and exactly match ASCII values, providing some degree of interoperability Values from 128 through 2047 use 16-bit encoding and provide support for Latin, Greek, Cyrillic, Hebrew, and Arabic alphabets Values 2048 through 65535 use 24-bit encoding for Chinese, Japanese, Korean, and other languages that require large numbers of values You can use the UTF8Encoding class to convert characters to and from UTF-8 encoding Unicode UTF-8 encoding ASCII encoding encodes the Latin alphabet as single 7-bit ASCII characters Because this encoding supports only character values from \u0000 through \u007F, in most cases it is inadequate for internationalized applications You can use the ASCIIEncoding class to convert characters to and from ASCII encoding ASCII encoding ANSI/ISO Encodings The System.Text.Encoding class provides support for a wide range of ANSI/ISO encodings MORE INFO Unicode For more information about Unicode, see the Unicode Standard at http://www.unicode.org Using the Encoding Class You can use the System.Text.Encoding.GetEncoding method to return an encoding object for a specified encoding You can use the Encoding.GetBytes method to convert a Unicode string to its byte representation in a specified encoding The following code example uses the Encoding.GetEncoding method to create a target encoding object for the Korean code page The code calls the Encoding.GetBytes method to convert a Unicode string to its byte representation in the Korean encoding The code then displays the byte representations of the strings in the Korean code page: ' VB ' Get Korean encoding Dim e As Encoding = Encoding.GetEncoding("Korean") ' Convert ASCII bytes to Korean encoding Dim encoded As Byte() encoded = e.GetBytes("Hello, World!") ' Display the byte codes Dim i As Integer Lesson 2: Encoding and Decoding 127 For i = To encoded.Length - Console.WriteLine("Byte {0}: {1}", i, encoded(i)) Next i // C# // Get Korean encoding Encoding e = Encoding.GetEncoding("Korean"); // Convert ASCII bytes to Korean encoding byte[] encoded; encoded = e.GetBytes("Hello, World!"); // Display the byte codes for (int i = 0; i < encoded.Length; i++) Console.WriteLine("Byte {0}: {1}", i, encoded[i]); This code sample demonstrates how to convert text to a different code page; however, normally you would not convert an English-language phrase into a different code page In most code pages, the code points through 127 represent the same ASCII characters This allows for continuity and for accommodating legacy code The code points 128 through 255 differ significantly between code pages Because the sample code translated the ASCII phrase, “Hello, World!” (which consists entirely of ASCII bytes falling in the range of code points from through 127), the translated bytes in the Korean code page exactly match the original ASCII bytes MORE INFO Code Pages For a list of all supported code pages, see the “Encoding Class” topic at http://msdn.microsoft.com/ en-us/library/system.text.encoding.aspx How to Examine Supported Code Pages To examine all supported code pages in the NET Framework, call Encoding.GetEncodings This method returns an array of EncodingInfo objects The following code sample displays the number, official name, and friendly name of the NET Framework code pages: ' VB Dim ei As EncodingInfo() = Encoding.GetEncodings For Each e As EncodingInfo In ei Console.WriteLine("{0}: {1}, {2}", e.CodePage, e.Name, e.DisplayName) Next // C# EncodingInfo[] ei = Encoding.GetEncodings(); foreach (EncodingInfo e in ei) Console.WriteLine("{0}: {1}, {2}", e.CodePage, e.Name, e.DisplayName); 128 Chapter Searching, Modifying, and Encoding Text How to Specify the Encoding Type When Writing a File To specify the encoding type when writing a file, use an overloaded Stream constructor that accepts an Encoding object For example, the following code sample creates several files with different encoding types: ' VB Dim swUtf7 As StreamWriter = New StreamWriter("utf7.txt", False, Encoding.UTF7) swUtf7.WriteLine("Hello, World!") swUtf7.Close Dim swUtf8 As StreamWriter = New StreamWriter("utf8.txt", False, Encoding.UTF8) swUtf8.WriteLine("Hello, World!") swUtf8.Close Dim swUtf16 As StreamWriter = New StreamWriter( _ "utf16.txt", False, Encoding.Unicode) swUtf16.WriteLine("Hello, World!") swUtf16.Close Dim swUtf32 As StreamWriter = New StreamWriter("utf32.txt", False, Encoding.UTF32) swUtf32.WriteLine("Hello, World!") swUtf32.Close // C# StreamWriter swUtf7 = new StreamWriter("utf7.txt", false, Encoding.UTF7); swUtf7.WriteLine("Hello, World!"); swUtf7.Close(); StreamWriter swUtf8 = new StreamWriter("utf8.txt", false, Encoding.UTF8); swUtf8.WriteLine("Hello, World!"); swUtf8.Close(); StreamWriter swUtf16 = new StreamWriter("utf16.txt", false, Encoding.Unicode); swUtf16.WriteLine("Hello, World!"); swUtf16.Close(); StreamWriter swUtf32 = new StreamWriter("utf32.txt", false, Encoding.UTF32); swUtf32.WriteLine("Hello, World!"); swUtf32.Close(); If you run the previous code sample, you will notice that the four different files each have different file sizes: the UTF-7 file is 19 bytes, the UTF-8 file is 18 bytes, the UTF-16 file is 32 bytes, and the UTF-32 file is 64 bytes If you open each of the files in Notepad, the UTF-8 and UTF-16 files display correctly However, the UTF-7 and UTF-32 files display incorrectly All the files were correctly encoded, but Notepad is not capable of reading UTF-7 and UTF-32 files correctly Lesson 2: Encoding and Decoding NOTE 129 Choosing an Encoding Type If you are not sure which encoding type to use when creating a file, simply accept the default by not specifying an encoding type The NET Framework then chooses UTF-16 How to Specify the Encoding Type When Reading a File Typically, you not need to specify an encoding type when reading a file The NET Framework automatically decodes most common encoding types However, you can specify an encoding type using an overloaded Stream constructor, as the following sample shows: ' VB Dim fn As String = "file.txt" Dim sw As StreamWriter = New StreamWriter(fn, False, Encoding.UTF7) sw.WriteLine("Hello, World!") sw.Close Dim sr As StreamReader = New StreamReader(fn, Encoding.UTF7) Console.WriteLine(sr.ReadToEnd) sr.Close // C# string fn = "file.txt"; StreamWriter sw = new StreamWriter(fn, false, Encoding.UTF7); sw.WriteLine("Hello, World!"); sw.Close(); StreamReader sr = new StreamReader(fn, Encoding.UTF7); Console.WriteLine(sr.ReadToEnd()); sr.Close(); Unlike most Unicode encoding types, the unusual UTF-7 encoding type in the previous code sample requires you to declare it explicitly when reading a file If you run the following code, which does not specify the UTF-7 encoding type when reading the file, it is read incorrectly and displays the wrong result: ' VB Dim fn As String = "file.txt" Dim sw As StreamWriter = New StreamWriter(fn, False, Encoding.UTF7) sw.WriteLine("Hello, World!") sw.Close Dim sr As StreamReader = New StreamReader(fn) Console.WriteLine(sr.ReadToEnd) sr.Close 130 Chapter Searching, Modifying, and Encoding Text // C# string fn = "file.txt"; StreamWriter sw = new StreamWriter(fn, false, Encoding.UTF7); sw.WriteLine("Hello, World!"); sw.Close(); StreamReader sr = new StreamReader(fn); Console.WriteLine(sr.ReadToEnd()); sr.Close(); Lab: Read and Write an Encoded File In this lab, you will convert a text file from one encoding type to another If you encounter a problem completing an exercise, the completed projects are available along with the sample files Exercise: Convert a Text File to a Different Encoding Type In this exercise, you will convert a text file to UTF-7 Use Visual Studio to create a new Console application Write code to read the C:\windows\win.ini file (or any text file), and then write it to a file named win-utf7.txt using the UTF-7 encoding type For example, the following code (which requires the System.IO namespace) would work: ' VB Dim sr As StreamReader = New StreamReader("C:\windows\win.ini") Dim sw As StreamWriter = New StreamWriter("win-utf7.txt", False, Encoding.UTF7) sw.WriteLine(sr.ReadToEnd) sw.Close() sr.Close() // C# StreamReader sr = new StreamReader(@"C:\windows\win.ini"); StreamWriter sw = new StreamWriter("win-utf7.txt", false, Encoding.UTF7); sw.WriteLine(sr.ReadToEnd()); sw.Close(); sr.Close(); Run your application and open the win-utf7.txt file in Notepad If the file was translated correctly, Notepad will display it with some invalid characters because Notepad does not support the UTF-7 encoding type Lesson Summary Encoding standards map byte values to characters ASCII is one of the oldest, most widespread encoding standards; however, it provides very limited support for non-English languages Today, various Unicode encoding standards provide multilingual support Lesson 2: Encoding and Decoding 131 The System.Text.Encoding class provides static methods for encoding and decoding text Call Encoding.GetEncodings to retrieve a list of supported code pages To specify the encoding type when writing a file, use an overloaded Stream constructor that accepts an Encoding object You typically not need to specify an encoding type when reading a file However, you can specify an encoding type by using an overloaded Stream constructor that accepts an Encoding object Lesson Review You can use the following questions to test your knowledge of the information in Lesson 2, “Encoding and Decoding.” The questions are also available on the companion CD if you prefer to review them in electronic form NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book Which of the following encoding types would yield the largest file size? A UTF-32 B UTF-16 C UTF-8 D ASCII Which of the following encoding types support Chinese? (Choose all that apply.) A UTF-32 B UTF-16 C UTF-8 D ASCII You need to decode a file encoded in ASCII Which of the following decoding types would yield correct results? (Choose all that apply.) A Encoding.UTF32 B Encoding.UTF16 ... demonstrates: '' VB i16 = i 32 i16 = db 60 Chapter Framework Fundamentals i 32 = i16 i 32 = db db = i16 db = i 32 // C# i16 = i 32; i16 = db; i 32 = i16; i 32 = db; db = i16; db = i 32; Attempt to build your... classes Manage NET Framework application data by using Reader and Writer classes Compress or decompress stream information in a NET Framework application and improve the security of application. .. used by text files Exam objectives in this chapter: Enhance the text handling capabilities of a NET Framework application and search, modify, and control text in a NET Framework application by using

Ngày đăng: 12/08/2014, 20:22

Từ khóa liên quan

Mục lục

  • Chapter 1: Framework Fundamentals

    • What Is Inheritance?

      • Lesson Summary

      • Lesson Review

      • Lesson 4: Converting Between Types

        • Conversion in Visual Basic and C#

        • What Are Boxing and Unboxing?

        • How to Implement Conversion in Custom Types

        • Lab: Safely Performing Conversions

        • Lesson Summary

        • Lesson Review

        • Chapter Review

        • Chapter Summary

        • Key Terms

        • Case Scenario

          • Case Scenario: Designing an Application

          • Suggested Practices

            • Manage Data in a .NET Framework Application by Using .NET Framework System Types

            • Implement .NET Framework Interfaces to Cause Components to Comply with Standard Contracts

            • Control Interactions Between .NET Framework Application Components by Using Events and Delegates

            • Take a Practice Test

            • Chapter 2: Input/Output

              • Before You Begin

              • Lesson 1: Working with the File System

                • Enumerating Drives

                • Managing Files and Folders

                • Monitoring the File System

Tài liệu cùng người dùng

Tài liệu liên quan