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

Visual studio 2010 part 10 docx

8 367 0

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

THÔNG TIN TÀI LIỆU

Nội dung

Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 81 Coding Fields and Properties A field is a variable that is a member of a class (type), as opposed to variables that are declared inside of methods, which are called local variables or locally scoped variables. Properties are type members that give you functionality that is a cross between fields and methods. You can read and write to a property just as you can to a field. Additionally, you can define code that runs whenever you read to or write from a property, similar to methods. The following sections define fields and properties. Declaring and Using Fields As stated, a field is a variable that is a member of a class (or some other container, such as a struct, which is very similar to a class). This provides the benefit of having the field and the data it contains available to all of the other members of the class (as well as to any deriving classes, via inheritance, depending on the field’s access modifier). To demonstrate how a field is declared and used, the example in Listing 3-8 simulates a bank account that has a field of type decimal named currentBalance, which holds an account balance. The class has two methods: Credit and Debit. Credit increases the value of currentBalance, and Debit decreases the value of currentBalance. Listing 3-8 Using fields and properties C#: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FirstProgram { class Program { private decimal accountBalance = 100m; static void Main(string[] args) { Program account = new Program(); account.Credit(100m); account.Debit(50m); Console.WriteLine("Balance: " + account.CurrentBalance); Console.ReadKey(); } 82 Microsoft Visual Studio 2010: A Beginner’s Guide public void Credit(decimal amount) { accountBalance += amount; } public void Debit(decimal amount) { accountBalance -= amount; } public decimal CurrentBalance { get { return accountBalance; } set { if (value < 0) { // charge fee } accountBalance = value; } } } } VB: Module Module1 Private Dim accountBalance As Decimal = 100 Sub Main() Credit(100) Debit(50) Console.WriteLine("Balance: " & CurrentBalance) Console.ReadKey() End Sub Sub Credit(ByVal amount As Decimal) accountBalance += amount End Sub Sub Debit(ByVal amount As Decimal) accountBalance -= amount End Sub Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 83 Public Property CurrentBalance() As Decimal Get Return accountBalance End Get Set(ByVal value As Decimal) If value < 0 Then ' charge fee End If accountBalance = value End Set End Property End Module Look at where accountBalance is declared: at the beginning of the Program (Module1 in VB) class block. It is at the same scope as Main and other methods, meaning that it is a member of Program (Module1 in VB), just like Main, Credit, and Debit. When variables like accountBalance are declared as class members, as opposed to local variables that are declared inside of method blocks, they are called fields. The accountBalance is type decimal, which is a good choice for holding financial values. The accountBalance field has a private modifier, which means that it can only be used by members of the same class. The implementations of Credit and Debit, respectively, increase and decrease the value of accountBalance. Since Credit and Debit are members of the same class as accountBalance, they’re allowed to read from and write to accountBalance. Main invokes Credit and Debit to change the value of the accountBalance field. Additionally, Main displays the value of accountBalance in the console window through a property named CurrentBalance. The next section explains how the CurrentBalance property works. Declaring and Using Properties Properties are class members that you use just like a field, but the difference is that you can add specialized logic when reading from or writing to a property. Listing 3-8 contains an example of a property, CurrentBalance, repeated as follows for your convenience: C#: public decimal CurrentBalance { get { return accountBalance; } 84 Microsoft Visual Studio 2010: A Beginner’s Guide set { if (value < 0) { // charge fee } accountBalance = value; } VB: Public Property CurrentBalance() As Decimal Get Return accountBalance End Get Set(ByVal value As Decimal) If value < 0 Then ' charge fee End If accountBalance = value End Set End Property Properties have accessors, named get and set, that allow you to add special logic when the property is used. When you read from a property, only the get accessor code executes, and the set accessor code only executes when you assign a value to a property. In the preceding example, the get accessor returns the value of currentBalance with no modifications. If there were some logic to apply, like calculating interest in addition to the current balance, the get accessor might have contained the logic for that calculation prior to returning the value. The set accessor does have logic that checks the value to see if it is less than zero, which could happen if a customer overdrew his or her account. If the value is less than zero, then you could implement logic to charge the customer a fee for the overdraft. The value keyword contains the value being assigned to the property, and the previous set accessor assigns value to the accountBalance field. The following statement from the Main method in Listing 3-8 reads from CurrentBalance, effectively executing the get accessor, which returns the value of currentBalance: C#: Console.WriteLine("Balance: " + account.CurrentBalance); VB: Console.WriteLine("Balance: " & CurrentBalance) Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 85 Since the CurrentBalance property returns the value of the accountBalance field, the Console.WriteLine statement will print the value read from CurrentBalance to the command line. Many of the properties you’ll write will simply be wrappers around current object state with no other logic, as in Listing 3-9. Listing 3-9 Property that wraps object state with no logic C#: private string m_firstName; public string FirstName { get { return m_firstName; } set { m_firstName = value; } } VB: Private m_firstName As String Public Property FirstName() As String Get Return m_firstName End Get Set(ByVal value As String) m_firstName = value End Set End Property In Listing 3-9, you can see that m_firstName, commonly referred to as a backing field, is a private variable and that the FirstName property only returns m_firstName from the get accessor and assigns the value to m_firstName in the set accessor. Since this is so common, you can save syntax by using an automatic property, as shown in Listing 3-10. 86 Microsoft Visual Studio 2010: A Beginner’s Guide Listing 3-10 Auto-implemented properties C#: public string FirstName { get; set; } VB: Public Property FirstName As String The automatic property, FirstName, is logically equivalent to the expanded FirstName with accessors and backing field. Behind the scenes, the compiler produces the expanded version where the backing field is guaranteed to have a unique name to avoid conflicts. Do not overlook that when you use automatic properties, you cannot add your own code that runs inside the get or set accessors. The Property Snippet To create a property snippet, type pro and press TAB, TAB; and you’ll see the property snippet template shown in Figure 3-4 for C# or Figure 3-5 for VB. A C# property snippet template creates an automatic property by default, but the VB snippet template is a normal property with full get and set accessors. Figure 3-5 The VB property snippet template Figure 3-4 The C# property snippet template Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 87 Summary You are now able to create classes to define your own custom types. After learning how to create classes and use class instances, also known as objects, you learned how to add fields, methods, and properties to your class definition. The methods discussion was more in-depth, showing you how to define parameters and return values. Y ou also learned how to define both auto-implemented and normal properties, and you learned a little about class inheritance. The next chapter moves you up a level in language skills by showing you how to create another type, called an interface. You’ll also learn how to add another type of class member, events. This page intentionally left blank . syntax by using an automatic property, as shown in Listing 3 -10. 86 Microsoft Visual Studio 2 010: A Beginner’s Guide Listing 3 -10 Auto-implemented properties C#: public string FirstName { get;. convenience: C#: public decimal CurrentBalance { get { return accountBalance; } 84 Microsoft Visual Studio 2 010: A Beginner’s Guide set { if (value < 0) { // charge fee } accountBalance. Console.WriteLine("Balance: " + account.CurrentBalance); Console.ReadKey(); } 82 Microsoft Visual Studio 2 010: A Beginner’s Guide public void Credit(decimal amount) { accountBalance += amount;

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