Tải bản đầy đủ (.pdf) (10 trang)

Visual studio 2010 part 9 potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (106.87 KB, 10 trang )

72 Microsoft Visual Studio 2010: A Beginner’s Guide
Just type in the class name in the field and press ENTER. The carat will locate to the
inside of the class block. Now that you know how to create classes, you’ll need to know
how to add members, starting with methods.
Writing Methods
You can divide your algorithms into blocks of code called methods. In different programming
languages, methods are called functions, procedures, or subroutines. I’ll use the term method
as a generic term, except when I need to be more specific. You’ve already used methods
when coding Console.WriteLine, where WriteLine is a method of the Console class. A
method contains one or more statements. Reasons for creating methods include the ability to
modularize your code, isolate complex operations in one place, or group a common operation
that can be reused in multiple places. The following sections show you how to declare and
use methods.
Declaring and Using a Method
To start off, I’ll show you a very simple method so that you can see the syntax and
understand the program flow. Listing 3-5 will move the Console.Writeline statement from
the Main method discussed in Chapter 2 into a new containing method and then add a
statement to the Main method that calls the new method.
Listing 3-5 Declaring and calling a method
C# (Program.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{


MessagePrinter msgPrint = new MessagePrinter();
msgPrint.PrintMessageInstance();
}
}
Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 73
C#: (MessagePrinter.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FirstProgram
{
class MessagePrinter
{
public static void PrintMessageStatic()
{
Console.WriteLine("Hello from a static method.");
}

public void PrintMessageInstance()
{
Console.WriteLine("Hello from an instance method.");
}
}
}
VB (Module1.vb):
Module Module1
Sub Main()
MessagePrinter.PrintMessageShared()


Dim msgPrint As New MessagePrinter()
msgPrinter.PrintMessageInstance()
End Sub
End Module
VB (MessagePrinter.vb)
Public Class MessagePrinter
Public Shared Sub PrintMessageShared()
Console.WriteLine("Hello from a shared method.")
End Sub

Public Sub PrintMessageInstance()
Console.WriteLine("Hello from an instance method.")
End Sub
End Class
74 Microsoft Visual Studio 2010: A Beginner’s Guide
Listing 3-5 has two types of methods, static and instance. In VB, shared methods are
the same as static. You can tell which type of method each is because static methods have
the static modifier (shared in VB), but instance methods don’t have a static (or shared in
VB) modifier. First, let’s look at the static (shared) method declaration, and then you’ll see
how it’s called.
The static (shared in VB) method, PrintMessageStatic (PrintMessageShared in VB)
has a public access modifier, which means that any other code using the containing class,
MessagePrinter, will be able to see the method. If you didn’t include the public access
modifier, the method would automatically default to being private and only other code
residing within the MessagePrinter class would be able to use that method.
PrintMessageStatic has a void keyword, meaning that this method does not return a
value. In VB, you indicate that a method does not return a value by making it a Sub, as
was done in Listing 3-5. Later, you’ll learn how to create a method that does return values
to its calling code that invokes this method. The empty parameter list appended to the

PrintMessageStatic (PrintMessageShared in VB) means that there are not any parameters
for this method. Parameters allow callers to pass information to the method; a subject
we’ll discuss soon.
Within the method block, you can see that there is a Console.WriteLine statement.
You can add as many statements as you need for the purpose of the method. Next, we’ll
examine how PrintMessageStatic (PrintMessageShared in VB) is called, which the
following code repeats from Listing 3-5:
C#:
Program.PrintMessageStatic();
VB:
MessagePrinter.PrintMessageShared()
Viewing the preceding example, which shows a statement inside of the Main method,
you can see the call to Program.PrintMessageStatic (PrintMessageShared in VB).
Notice that the class (aka type) that contains all the methods is named MessagePrinter.
In C#, a static method is called through its containing type, which is why you call
PrintMessageStatic with the Program prefix. In VB, you can invoke shared methods
through either the method’s type or an instance of that type. We discuss instance
methods next.
The next method, PrintMessageInstance, is an instance method; it has no static
modifier. The rest of the method definition mirrors that of the PrintMessageStatic method.
Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 75
Since PrintMethodInstance is an instance method, you call it differently; through an
instance of its containing type, which the following code repeats from Listing 3-5:
C#:
MessagePrinter msgPrint = new MessagePrinter();
msgPrint.PrintMessageInstance();
VB:
Dim msgPrint As New MessagePrinter()
msgPrinter.PrintMessageInstance()
As this example shows, the type of msgPrint is MessagePrinter. Using the statement new

MessagePrinter creates a new instance of MessagePrinter at runtime, which is assigned to the
msgPrint variable. Now that you’ve created an instance of a MessagePrinter and msgPrint
has a reference to that instance, you can call the instance method, PrintMessageInstance, via
the msgPrint variable. Next, let’s look at how to add parameters to a method and discuss why
that’s important.
Declaring Parameters and Passing Arguments
Passing parameters to a method is a great way to make code more reusable. For example,
what if you had a method that printed a report containing the names of all customers? It
wouldn’t make sense to create one method for each customer, especially when the list
changes all the time. Listing 3-6 shows a method that takes a list of customers and prints
a report with customer names.
Listing 3-6 Declaring a method that takes parameters
C# (Program.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FirstProgram
{
class Program
{
static void Main(string[] args)
76 Microsoft Visual Studio 2010: A Beginner’s Guide
{
MessagePrinter msgPrint = new MessagePrinter();

string[] customerNames = { "Jones", "Smith", "Mayo" };
string reportTitle = "Important Customer Report";


msgPrint.PrintCustomerReport(customerNames, reportTitle);
}
}
C# (MessagePrinter.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FirstProgram
{
public void PrintCustomerReport(
string[] customers, string title = "Customer Report")
{
Console.WriteLine(title);
Console.WriteLine();

foreach (var name in customers)
{
Console.WriteLine(name);
}
}
}
}
VB (Module1.vb):
Module Module1
Sub Main()
Dim msgPrint As New MessagePrinter()

Dim customerNames = {"Jones", "Smith", "Mayo"}

Dim reportTitle As String = "Important Customer Report"

msgPrint.PrintCustomerReport(customerNames, reportTitle)
End Sub
End Module
Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 77
VB (MessagePrinter.vb):
Public Class MessagePrinter
Sub PrintCustomerReport(ByVal customers As String(), ByVal title
As String)
Console.WriteLine(title)
Console.WriteLine()

For Each name In customers
Console.WriteLine(name)
Next
End Sub
End Class
Parameters are a comma-separated list of identifiers, along with the type of each
identifier, which clearly indicates what type of parameter the method is expecting. In
Listing 3-6, the PrintCustomerReport method has two parameters: title of type string and
customers of type string array. The method displays the title in the console window when
you run the program, displays a blank line, and then iterates through the list, displaying
each customer name to the console.
You can see how the Main method creates a new instance of MessagePrinter,
which msgPrint points to, and then calls PrintCustomerReport using msgPrint. The
arguments being passed, reportTitle and customerNames, match the position and types
of the parameters for PrintCustomerReport, which are of the correct types that the
PrintCustomerReport method is expecting.
In the preceding example, the calling code must provide arguments, actual data,

for all parameters. However, you can specify parameters as being optional, allowing
you to omit arguments for the optional parameters if you like. Here’s a modification to
PrintCustomerReport where the title becomes an optional parameter:
C#:
public void PrintCustomerReport(
string[] customers, string title = "Customer Report")
{
Console.WriteLine(title);
Console.WriteLine();

foreach (var name in customers)
{
Console.WriteLine(name);
}
}
78 Microsoft Visual Studio 2010: A Beginner’s Guide
VB:
Sub PrintCustomerReport(
ByVal customers As String(),
Optional ByVal title As String = "Customer Report")

Console.WriteLine(title)
Console.WriteLine()

For Each name In customers
Console.WriteLine(name)
Next
End Sub
The preceding code requires callers to pass an array of customers, but it does not
require a title. When writing methods, optional parameters must be listed last. Here’s

a method call without the optional parameter:
C#:
custProg.PrintCustomerReport(customerNames);
VB:
msgPrint.PrintCustomerReport(customerNames)
Because the caller didn’t pass an argument for title, the value of title inside of
PrintCustomerReport becomes the default value assigned to the title parameter.
In addition to passing arguments to methods, you can receive values returned from
methods.
Returning Data and Using Method Results
It is common to call methods that return values. To demonstrate the proper syntax,
Listing 3-7 contains a method that accepts an int and returns the squared value of
that int. Calling code then assigns the return value from the method to a variable and
displays the value on the console window. Create a new class named Calc.cs or Calc.
vb to hold the new method.
Listing 3-7 Returning values from methods
C# (Program.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 79
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
Calc mathProg = new Calc();


int squaredInt = mathProg.SquareInt(3);
Console.WriteLine("3 squared is " + squaredInt);

Console.ReadKey();
}
}
}
C# (Calc.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FirstProgram
{
public class Calc
{
public int SquareInt(int number)
{
return number * number;
}
}
}
VB (Module1.vb):
Module Module1

Sub Main()
Dim mathProg As New Calc()
Dim squaredInt As Integer = mathProg.SquareInt(3)

Console.WriteLine("3 squared is " & squaredInt)
End Sub
End Module
80 Microsoft Visual Studio 2010: A Beginner’s Guide
VB (Calc.vb):
Public Class Calc
Public Function SquareInt(ByVal number As Integer) As Integer
Return number * number
End Function
End Class
For the C# example, notice how the return type of the SquareInt method is type int,
rather than the keyword void that was used in our methods before. Whenever you specify
a return type, the method must return something whose type is the same as the return
type declared. In the preceding example, the return type is declared as int; therefore, the
method guarantees that the result of the calculation is type int. The Main method has
a couple of statements that invoke this method and display the results to the console.
In the VB example, the method is now a Function. Sub methods don’t return values.
Notice how the function signature appends As Integer after the parameter list, which
indicates that the return type of the function is Integer.
Method Snippets
C# doesn’t have snippets for writing methods (although you could create your own
snippets), but VB does. In VB, type Sub,
TAB, TAB; producing the template shown in
Figure 3-2; or Fun,
TAB, TAB; producing the template shown in Figure 3-3.
Figure 3-2 The VB sub snippet template
Figure 3-3 The VB function snippet template
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();
}

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×