1. Trang chủ
  2. » Công Nghệ Thông Tin

Visual studio 2010 part 12 pot

17 115 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 17
Dung lượng 183,5 KB

Nội dung

96 Microsoft Visual Studio 2010: A Beginner’s Guide As you can see, the Editor pops up a tooltip instructing you to type TAB to create a new delegate instance. Type TAB and Code Completion will pop up another tooltip for creating the handler method, as shown in Figure 4-2. In Figure 4-2, you can see that Code Completion is suggesting a method name for you. You have a choice of pressing TAB or changing the method name and then pressing TAB. Either way, you have a fast way to hook up a handler method to an event via the event’s delegate type. Just as a delegate provides an interface to a method that is a contract basically to describe how to communicate, you can also define interfaces to classes to communicate with them in a specified way, and these are intuitively named . . . interfaces. Implementing Interfaces Another language feature that gives you flexibility is interfaces. An interface can be useful if you want to have a group of classes that can be interchanged at any time, yet you need to write the same operations for each of these classes. Essentially, you want to write the code that uses the class only one time, but still switch what the actual class is. That’s where interfaces come in. The interface creates a contract that each of the interchangeable classes must adhere to. So, if the interface says that all classes that implement the interface have method A and property B, then every class that implements the interface must have method A and property B; the compiler enforces this like a contract that cannot be broken. The following sections show you how to write an interface and then build a couple of classes that implement that interface. Finally, you’ll see how to write code against the interface. One important fact to remember about interfaces is that they don’t have any code other than definitions of members. This definition of members is the contract of the interface. You are the one who must to write a class that contains the members of the interface, and you must write the code that provides an implementation of the interface members. A common point of confusion is that an interface does not have any executable code, but the classes that implement the interfaces do. The following sections show you how to create an interface, how to create a class that has code (that you’ve written) to implement the interface contract, and how to write code that operates on the classes that implement (guarantee the contract of) the interface. Figure 4-2 Code completion for handler method creation Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 97 Creating an Interface To create an interface, right-click the project in Solution Explorer, select Add | New Item, select Code under the language branch in Installed Templates, and select the Interface item. Name the Interface IAccount and click Add. By standard convention, you will always name any interface class you create with a name that starts with an uppercase letter I. You’ll see the interface in Listing 4-2 added to your project: Listing 4-2 An interface C#: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FirstProgram { public interface IAccount { void Credit(decimal amount); void Debit(decimal amount); decimal CurrentBalance { get; set; } } } VB: Public Interface IAccount Sub Credit(ByVal amount As Decimal) Sub Debit(ByVal amount As Decimal) Property CurrentBalance As Decimal End Interface After you’ve added the interface, you’ll need to make modifications to make the code match Listing 4-2. Notice that the IAccount members don’t have an implementation and so appear incomplete because they have no lines of code. Also, each member doesn’t have a public modifier, because interface members are implicitly public. The following sections show you how to build the classes that implement the IAccount interface; there, you should begin to see the benefit that an interface can bring. 98 Microsoft Visual Studio 2010: A Beginner’s Guide Making Classes Implement the Interface To create a class, right-click the project in Solution Explorer, select Add | New Item, select Code under the language branch in Installed Templates, and select the Class item. Name the class Checking and click Add. Using the same procedure as Checking, add another class, but name it Saving. Listings 4-3 and 4-4 show the two new classes. Listing 4-3 Checking class that implements IAccount interface C#: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FirstProgram { class Checking : IAccount { public void Credit(decimal amount) { // implement checking logic CurrentBalance += amount; Console.Writeline("Added " + amount.ToString() + " to Checking Account"); } public void Debit(decimal amount) { // implement checking logic CurrentBalance -= amount; Console.Writeline("Debited " + amount.ToString() + " from Checking Account"); } public decimal CurrentBalance { get; set; } } } VB: Public Class Checking Implements IAccount Public Sub Credit(ByVal amount As Decimal) Implements IAccount. Credit Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 99 ' Implement Checking logic CurrentBalance += amount Console.Writeline("Added " & amount.ToString() & " to Checking Account") End Sub Public Sub Debit(ByVal amount As Decimal) Implements IAccount.Debit ' Implement Checking logic CurrentBalance -= amount Console.Writeline("Debited " + amount.ToString() + " from Checking Account") End Sub Public Property CurrentBalance As Decimal Implements IAccount. CurrentBalance End Class Listing 4-4 Saving class that implements IAccount interface C#: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FirstProgram { class Saving : IAccount { public void Credit(decimal amount) { // implement savings logic CurrentBalance += amount; Console.Writeline("Added " + amount.ToString() + " to Saving Account"); } public void Debit(decimal amount) { // implement savings logic CurrentBalance -= amount; Console.Writeline("Debited " + amount.ToString() + " from Saving Account"); } 100 Microsoft Visual Studio 2010: A Beginner’s Guide public decimal CurrentBalance { get; set; } } } VB: Public Class Saving Implements IAccount Public Sub Credit(ByVal amount As Decimal) Implements IAccount. Credit ' Implement Saving logic CurrentBalance += amount Console.Writeline("Added " & amount.ToString() & " to Saving Account") End Sub Public Sub Debit(ByVal amount As Decimal) Implements IAccount.Debit ' Implement Saving logic CurrentBalance -= amount Console.Writeline("Debited " + amount.ToString() + " from Saving Account") End Sub Public Property CurrentBalance As Decimal Implements IAccount.CurrentBalance End Class In both Listings 4-3 and 4-4, notice that the Checking and Saving, respectively, implement the IAccount interface, repeated as follows: C#: class Checking : IAccount and class Saving : IAccount VB: Public Class Checking Implements IAccount and Public Class Saving Implements IAccount Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 101 In the C# listing, following the class name by a colon and then the interface name specifies that the class will implement the interface. The VB listing uses the Implements keyword to indicate that Checking and Saving classes implement the IAccount interface. Looking at both Checking and Saving, you can see that they have the Credit, Debit, and CurrentBalance members that are specified in IAccount. The primary difference is that IAccount doesn’t have an implementation, but you wrote an implementation for Checking and Saving. Listings 4-3 and 4-4 simplify the implementation of the interface so that you don’t have to read a lot of code that doesn’t add to the purpose of the listing to show you how a class implements an interface. In reality, the code in the methods would be different for Checking and Saving because they are different account types with different business rules. You’ve created an interface and written classes to implement the contract of that interface. The next section gives you a couple of examples to help clarify the practical use of interfaces. Writing Code That Uses an Interface One of the best ways to understand the value of interfaces is to see a problem that interfaces solve. In this section, I’ll show you some code that accesses the Checking and Saving classes individually, essentially duplicating code. Then I’ll show you how to write the code a single time with interfaces. The particular example runs a payroll by obtaining instances of Checking and Saving classes and crediting each class, which is synonymous with employees being paid. Starting with the bad example, Listing 4-5 shows how this code works. Listing 4-5 Processing payroll with explicit checking and saving class instances C#: public void ProcessPayrollForCheckingAndSavingAccounts() { Checking[] checkAccounts = GetCheckingAccounts(); foreach (var checkAcct in checkAccounts) { checkAcct.Credit(500); } 102 Microsoft Visual Studio 2010: A Beginner’s Guide Saving[] savingAccounts = GetSavingAccounts(); foreach (var savingAcct in savingAccounts) { savingAcct.Credit(500); } } public Checking[] GetCheckingAccounts() { Checking[] chkAccts = new Checking[2]; chkAccts[0] = new Checking(); chkAccts[1] = new Checking(); return chkAccts; } public Saving[] GetSavingAccounts() { int numberOfAccounts = 5; Saving[] savAccts = new Saving[numberOfAccounts]; for (int i = 0; i < numberOfAccounts; i++) { savAccts[i] = new Saving(); } return savAccts; } VB: Sub ProcessPayrollForCheckingAndSavingAccounts() Dim checkAccounts As Checking() = GetCheckingAccounts() For Each checkAcct In checkAccounts checkAcct.Credit(500) Next Dim savingAccounts As Saving() = GetSavingsAccounts() For Each savingAcct In savingAccounts savingAcct.Credit(500) Next End Sub Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 103 Function GetCheckingAccounts() As Checking() Dim chkAccts(1) As Checking chkAccts(0) = New Checking() chkAccts(1) = New Checking() Return chkAccts End Function Function GetSavingsAccounts() As Saving() Dim numberOfAccounts As Integer = 5 Dim savAccts(numberOfAccounts) As Saving For i As Integer = 0 To numberOfAccounts savAccts(i) = New Saving() Next Return savAccts End Function To save space, I haven’t included the entire application in Listing 4-5, which is available with the source code for this book via the McGraw-Hill W eb site. To understand how it works, imagine that you’ve written the following code in the Main method: C#: Program bank = new Program(); bank.ProcessPayrollForCheckingAndSavingAccounts(); VB: ProcessPayrollForCheckingAndSavingAccounts() Walking through the code, let’s start at the ProcessPayrollForCheckingAndSaving Accounts method. You can see how the algorithm calls GetCheckingAccounts to retrieve an array of Checking objects. If you recall, an array is a list of elements of a specified type, that type being Checking in this case. The algorithm goes on to iterate through the Checking objects, invoking Credit on each to add 500 to the account. Some employees want their paychecks in Checking, but others might want their paychecks to go into Saving (or some other account). Therefore, the algorithm calls GetSavingsAccounts to get a list of those accounts for employees who want their paychecks to go into their savings. You’ll notice that the algorithm inside of GetSavingsAccounts is different from 104 Microsoft Visual Studio 2010: A Beginner’s Guide GetCheckingAccounts, which I did on purpose so that you’ll see different ways to use loops; but this doesn’t affect the calling code because it’s encapsulated in individual methods. The point to make here is that GetCheckingAccounts will only return Checking class instances and GetSavingsAccounts will only return Saving class instances. The rest of the algorithm in the ProcessPayrollForCheckingAndSavingAccounts method mirrors the processing for Checking. What should catch your attention is the duplication of code in the ProcessPayroll ForCheckingAndSavingAccounts method. Although the Credit methods of Checking and Saving should have different implementations, the code calling Credit can be the same, eliminating duplication. Listing 4-6 shows how to take advantage of the fact that both Checking and Saving implement the same interface, IAccount. You’ll see how to call Credit on any IAccount-derived type with one algorithm, eliminating the duplication you saw in Listing 4-5. Listing 4-6 Processing payroll through the IAccount interface C#: public void ProcessPayrollForAllAccounts() { IAccount[] accounts = GetAllAccounts(); foreach (var account in accounts) { account.Credit(1000); } } public IAccount[] GetAllAccounts() { IAccount[] allAccounts = new IAccount[4]; allAccounts[0] = new Checking(); allAccounts[1] = new Saving(); allAccounts[2] = new Checking(); allAccounts[3] = new Saving(); return allAccounts; } Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 105 VB: Sub ProcessPayrollForAllAccounts() Dim accounts As IAccount() = GetAllAccounts() For Each account In accounts account.Credit(1000) Next End Sub Function GetAllAccounts() As IAccount() Dim allAccounts(3) As IAccount allAccounts(0) = New Checking() allAccounts(1) = New Saving() allAccounts(2) = New Checking() allAccounts(3) = New Saving() Return allAccounts End Function You can call the code in Listing 4-6 from the Main method like this: C#: Program bank = new Program(); bank.ProcessPayrollForAllAccounts(); VB: ProcessPayrollForAllAccounts() Examining Listing 4-6, you can see that accounts is an array of IAccount. While you can’t instantiate an interface by itself, you can assign an instance of the class that implements that interface using a variable simply declared as the interface type. In this case, GetAllAccounts returns a list of objects that implement IAccount. Looking inside of the GetAllAccounts method, you can see how an array is being built with both Checking and Saving objects. Since Checking and Saving implement IAccount, which you saw in Listings 4-3 and 4-4, instances of Checking and Saving can be directly assigned into elements of an IAccount array. Back in the ProcessPayrollForAllAccounts method, you can see a loop iterate through each IAccount instance, calling Credit. The reason you can call Credit like this is that IAccount defines a contract for the Credit method. Calling Credit on each instance really [...]...106 Microsoft Visual Studio 2010: A Beginner’s Guide Figure 4-3 The C# interface snippet template invokes the Credit method on the runtime Checking or Saving instance Your code that you wrote for Checking.Credit and Saving.Credit... stats[2] = 3.3; double sum = 0; for (int i = 0; i < stats.Length; i++) { sum += stats[i]; } Console.WriteLine( stats[0] + " + " + stats[1] + " + " + stats[2] + " = " + sum); } 107 108 Microsoft Visual Studio 2010: A Beginner’s Guide VB: Sub ArrayDemo() Dim stats(2) As Double stats(0) = 1.1 stats(1) = 2.2 stats(2) = 3.3 Dim sum As Double = 0 For i As Integer = 0 To 2 sum += stats(i) Next Console.WriteLine(... Checking) checkAccts.Add(New Checking()) checkAccts.Add(New Checking()) For i As Integer = 0 To checkAccts.Count - 1 Console.WriteLine(checkAccts(i).CurrentBalance) Next End Sub 109 110 Microsoft Visual Studio 2010: A Beginner’s Guide In NET, the generic List type is declared as List, or List(Of T) in VB The T is a type placeholder, where you can specify any type you want For example, you could create... to C# and VB and that there is much more to learn about these languages Of course, this book is about VS and not languages, so the next chapter is where you’ll learn to build VS projects Part II Learning the VS 2010 Environment This page intentionally left blank ... will typically need to group objects into a single collection of that object type For this, you can use an array, which is a container that can have zero or many elements, each holding an instance of a particular type You’ll soon see how to use an array to locate the elements (items) you want There are also generic collection classes in the NET Framework that are even more powerful than arrays You’ll . 96 Microsoft Visual Studio 2010: A Beginner’s Guide As you can see, the Editor pops up a tooltip instructing you to. interface; there, you should begin to see the benefit that an interface can bring. 98 Microsoft Visual Studio 2010: A Beginner’s Guide Making Classes Implement the Interface To create a class, right-click. " + amount.ToString() + " from Saving Account"); } 100 Microsoft Visual Studio 2010: A Beginner’s Guide public decimal CurrentBalance { get; set; } } } VB: Public Class

Ngày đăng: 04/07/2014, 03:20