楼主: bnso

Introduction to C# Programming

[复制链接]
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
41#
 楼主| 发表于 2006-8-13 21:14 | 只看该作者
Module 5: Methods and Parameters 5
Calling Methods
n After You Define a Method, You Can:
l Call a method from within the same class
Use method’s name followed by a parameter list in
parentheses
l Call a method that is in a different class
You must indicate to the compiler which class contains
the method to call
The called method must be declared with the public
keyword
l Use nested calls
Methods can call methods, which can call other
methods, and so on
After you define a method, you can call it from within the same class and from
other classes.
Calling Methods
To call a method, use the name of the method followed by a parameter list in
parentheses. The parentheses are required even if the method that you call has
no parameters, as shown in the following example.
MethodName( );
There is no Call statement Parentheses are
required for all method calls.
Note to Visual Basic Developers
6 Module 5: Methods and Parameters
In the following example, the program begins at the start of the Main method
of ExampleClass. The first statement displays “The program is starting.” The
second statement in Main is the call to ExampleMethod. Control flow passes
to the first statement within ExampleMethod, and “Hello, world” appears. At
the end of the method, control passes to the statement immediately following
the method call, which is the statement that displays “The program is ending.”
using System;
class ExampleClass
{
static void ExampleMethod( )
{
Console.WriteLine("Hello, world";
}
static void Main( )
{
Console.WriteLine("The program is starting";
ExampleMethod( );
Console.WriteLine("The program is ending";
}
}
Calling Methods from Other Classes
To allow methods in one class to call methods in another class, you must:
n Specify which class contains the method you want to call.
To specify which class contains the method, use the following syntax:
ClassName.MethodName( );
n Declare the method that is called with the public keyword.
The following example shows how to call the method TestMethod, which is
defined in class A, from Main in class B:
using System;
class A
{
public static void TestMethod( )
{
Console.WriteLine("This is TestMethod in class A";
}
}
class B
{
static void Main( )
{
A.TestMethod( );
}
}
Module 5: Methods and Parameters 7
If, in the example above, the class name were removed, the compiler would
search for a method called TestMethod in class B. Since there is no method of
that name in that class, the compiler will display the following error: “The name
‘TestMethod’ does not exist in the class or namespace ‘B.’”
If you do not declare a method as public, it becomes private to the class by
default. For example, if you omit the public keyword from the definition of
TestMethod, the compiler will display the following error: “A.TestMethod() is
inaccessible due to its protection level.”
You can also use the private keyword to specify that the method can only be
called from inside the class. The following two lines of code have exactly the
same effect because methods are private by default:
private static void MyMethod( );
static void MyMethod( );
The public and private keywords shown above specify the accessibility of the
method. These keywords control whether a method can be called from outside
of the class in which it is defined.
Nesting Method Calls
You can also call methods from within methods. The following example shows
how to nest method calls:
using System;
class NestExample
{
static void Method1( )
{
Console.WriteLine("Method1"
}
static void Method2( )
{
Method1( );
Console.WriteLine("Method2"
Method1( );
}
static void Main( )
{
Method2( );
Method1( );
}
}

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
42#
 楼主| 发表于 2006-8-13 21:15 | 只看该作者
8 Module 5: Methods and Pa rameters
The output from this program is as follows:
Method1
Method2
Method1
Method1
You can call an unlimited number of methods by nesting. There is no
predefined limit to the nesting level. However, the run-time environment might
impose limits, usually because of the amount of RAM available to perform the
process. Each method call needs memory to store return addresses and other
information.
As a general rule, if you are running out of memory for nested method calls,
you probably have a class design problem.
Module 5: Methods and Parameters 9
Using the return Statement
n Immediate Return
n Return with a Conditional Statement
static void ExampleMethod( )
{
int numBeans;
//...
Console.WriteLine("Hello";
if (numBeans < 10)
return;
Console.WriteLine("World";
}
static void ExampleMethod( )
{
int numBeans;
//...
Console.WriteLine("Hello";
if (numBeans < 10)
return;
Console.WriteLine("World";
}
You can use the return statement to make a method return immediately to the
caller. Without a return statement, execution usually returns to the caller when
the last statement in the method is reached.
Immediate Return
By default, a method returns to its caller when the end of the last statement in
the code block is reached. If you want a method to return immediately to the
caller, use the return statement.
In the following example, the method will display “Hello,” and then
immediately return to its caller:
static void ExampleMethod( )
{
Console.WriteLine("Hello";
return;
Console.WriteLine("World";
}
Using the return statement like this is not very useful because the final call to
Console.WriteLine is never executed. If you have enabled the C# compiler
warnings at level 2 or higher, the compiler will display the following message:
“Unreachable code detected.”
10 Module 5: Methods and Parameters
Return with a Conditional Statement
It is more common, and much more useful, to use the return statement as part
of a conditional statement such as if or switch. This allows a method to return
to the caller if a given condition is met.
In the following example, the method will return if the variable numBeans is
less than 10; otherwise, execution will continue within this method.
static void ExampleMethod( )
{
int numBeans;
//...
Console.WriteLine("Hello";
if (numBeans < 10)
return;
Console.WriteLine("World";
}
It is generally regarded as good programming style for a method to have
one entry point and one exit point. The design of C# ensures that all methods
begin execution at the first statement. A method with no return statements has
one exit point, at the end of the code block. A method with multiple return
statements has multiple exit points, which can make the method difficult to
understand and maintain in some cases.
Return with a Value
If a method is defined with a data type rather than void, the return mechanism is
used to assign a value to the function. This will be discussed later in this
module.
Tip

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
43#
 楼主| 发表于 2006-8-13 21:15 | 只看该作者
Module 5: Methods and Parameters 11
Using Local Variables
n Local Variables
l Created when method begins
l Private to the method
l Destroyed on exit
n Shared Variables
l Class variables are used for sharing
n Scope Conflicts
l Compiler will not warn if local and class names clash
Each method has its own set of local variables. You can use these variables
only inside the method in which they are declared. Local variables are not
accessible from elsewhere in the application.
Local Variables
You can include local variables in the body of a method, as shown in the
following example:
static void MethodWithLocals( )
{
int x = 1; // Variable with initial value
ulong y;
string z;
}
You can assign local variables an initial value. (For an example, see variable x
in the preceding code.) If you do not assign a value or provide an initial
expression to determine a value, the variable will not be initialized.
The variables that are declared in one method are completely separate from
variables that are declared in other methods, even if they have the same names.
Memory for local variables is allocated each time the method is called and
released when the method terminates. Therefore, any values stored in these
variables will not be retained from one method call to the next.
12 Module 5: Methods and Parameters
Shared Variables
Consider the following code, which attempts to count the number of times a
method has been called:
class CallCounter_Bad
{
static void Init( )
{
int nCount = 0;
}
static void CountCalls( )
{
int nCount;
++nCount;
Console.WriteLine("Method called {0} time(s)", nCount);
}
static void Main( )
{
Init( );
CountCalls( );
CountCalls( );
}
}
This program cannot be compiled because of two important problems. The
variable nCount in Init is not the same as the variable nCount in CountCalls.
No matter how many times you call the method CountCalls, the value nCount
is lost each time CountCalls finishes.
The correct way to write this code is to use a class variable, as shown in the
following example:
class CallCounter_Good
{
static int nCount;
static void Init( )
{
nCount = 0;
}
static void CountCalls( )
{
++nCount;
Console.Write("Method called " + nCount + " time(s).";
}
static void Main( )
{
Init( );
CountCalls( );
CountCalls( );
}
}
In this example, nCount is declared at the class level rather than at the method
level. Therefore, nCount is shared between all of the methods in the class.
Module 5: Methods and Parameters 13
Scope Conflicts
In C#, you can declare a local variable that has the same name as a class
variable, but this can produce unexpected results. In the following example,
NumItems is declared as a variable of class ScopeDemo, and also declared as a
local variable in Method1. The two variables are completely different. In
Method1, numItems refers to the local variable. In Method2, numItems refers
to the class variable.
class ScopeDemo
{
static int numItems = 0;
static void Method1( )
{
int numItems = 42;
}
static void Method2( )
{
numItems = 61;
}
}
Because the C# compiler will not warn you when local variables and class
variables have the same names, you can use a naming convention to distinguish
local variables from class variables.
Tip

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
44#
 楼主| 发表于 2006-8-13 21:16 | 只看该作者
14 Module 5: Methods and Parameters
Returning Values
n Declare the Method with Non-Void Type
n Add a return Statement with an Expression
l Sets the return value
l Returns to caller
n Non-void Methods Must Return a Value
static int TwoPlusTwo( ) {
int a,b;
a = 2;
b = 2;
return a + b;
}
static int TwoPlusTwo( ) {
int a,b;
a = 2;
b = 2;
return a + b;
}
int x;
x = TwoPlusTwo( );
Console.WriteLine(x);
int x;
x = TwoPlusTwo( );
Console.WriteLine(x);
You have learned how to use the return statement to immediately terminate a
method. You can also use the return statement to return a value from a method.
To return a value, you must:
1. Declare the method with the value type that you want to return.
2. Add a return statement inside the method.
3. Include the value that you want to return to the caller.
Declaring Methods with Non-Void Type
To declare a method so that it will return a value to the caller, replace the void
keyword with the type of the value that you want to return.
Adding return Statements
The return keyword followed by an expression terminates the method
immediately and returns the expression as the return value of the method.
Module 5: Methods and Parameters 15
The following example shows how to declare a method named TwoPlusTwo
that will return a value of 4 to Main when TwoPlusTwo is called:
class ExampleReturningValue
{
static int TwoPlusTwo( )
{
int a,b;
a = 2;
b = 2;
return a + b;
}
static void Main( )
{
int x;
x = TwoPlusTwo( );
Console.WriteLine(x);
}
}
Note that the returned value is an int. This is because int is the return type of
the method. When the method is called, the value 4 is returned. In this example,
the value is stored in the local variable x in Main.
Non-Void Methods Must Return Values
If you declare a method with a non-void type, you must add at least one return
statement. The compiler attempts to check that each non-void method returns a
value to the calling method in all circumstances. If the compiler detects that a
non-void method has no return statement, it will display the following error
message: “Not all code paths return a value.” You will also see this error
message if the compiler detects that it is possible to execute a non-void method
without returning a value.
In the following example, you will get a valid return statement if the value in x
is less than two. If the value in x is greater than or equal to two, the compiler
will report an error because the return statement is not executed, and the
method execution will terminate after the if statement without returning a value.
static int BadReturn( )
{
// ...
if (x < 2)
return 5;
}
You can only use the return statement to return one value from each
method call. If you need to return more than one value from a method call, you
can use the ref or out parameters, which are discussed later in this module.
Alternatively, you can return a reference to an array or class, which can contain
multiple values. The general guideline that says to avoid using multiple return
statements in a single method applies equally to non-void methods.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
45#
 楼主| 发表于 2006-8-13 21:16 | 只看该作者
16 Module 5: Methods and Parameters
u Using Parameters
n Declaring and Calling Parameters
n Mechanisms for Passing Parameters
n Pass by Value
n Pass by Reference
n Output Parameters
n Using Variable-Length Parameter Lists
n Guidelines for Passing Parameters
n Using Recursive Methods
In this section, you will learn how to declare parameters and how to call
methods with parameters. You will also learn how to pass parameters. Finally,
you will learn how C# supports recursive method calls.
In this section you will learn how to:
n Declare and call parameters.
n Pass parameters by using the following mechanisms:
· Pass by value
· Pass by reference
· Output parameters
n Use recursive method calls.
Module 5: Methods and Parameters 17
Declaring and Calling Parameters
n Declaring Parameters
l Place between parentheses after method name
l Define type and name for each parameter
n Calling Methods with Parameters
l Supply a value for each parameter
static void MethodWithParameters(int n, string y)
{ ... }
MethodWithParameters(2, "Hello, world";
static void MethodWithParameters(int n, string y)
{ ... }
MethodWithParameters(2, "Hello, world";
Parameters allow information to be passed into and out of a method. When you
define a method, you can include a list of parameters in parentheses following
the method name. In the examples so far in this module, the parameter lists
have been empty.
Declaring Parameters
Each parameter has a type and a name. You declare parameters by placing the
parameter declarations inside the parentheses that follow the name of the
method. The syntax that is used to declare parameters is similar to the syntax
that is used to declare local variables, except that you separate each parameter
declaration with a comma instead of with a semicolon.
The following example shows how to declare a method with parameters:
static void MethodWithParameters(int n, string y)
{
// ...
}
This example declares the MethodWithParameters method with two
parameters: n and y. The first parameter is of type int, and the second is of type
string. Note that commas separate each parameter in the parameter list.
18 Module 5: Methods and Parameters
Calling Methods with Parameters
The calling code must supply the parameter values when the method is called.
The following code shows two examples of how to call a method with
parameters. In each case, the values of the parameters are found and placed into
the parameters n and y at the start of the execution of MethodWithParameters.
MethodWithParameters(2, "Hello, world";
int p = 7;
string s = "Test message";
MethodWithParameters(p, s);
Module 5: Methods and Parameters 19
Mechanisms for Passing Parameters
n Three Ways to Pass Parameters:
iinn PPaassss bbyy vvaalluuee
in
out
in
out PPaassss bbyy rreeffeerreennccee
oouutt OOuuttppuutt ppaarraammeetteerrss
Parameters can be passed in three different ways:
n By value
Value parameters are sometimes called in parameters because data can be
transferred into the method but cannot be transferred out.
n By reference
Reference parameters are sometimes called in/out parameters because data
can be transfer red into the method and out again.
n By output
Output parameters are sometimes called out parameters because data can be
transferred out of the method but cannot be transferred in.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
46#
 楼主| 发表于 2006-8-13 21:17 | 只看该作者
20 Module 5: Methods and Parameters
Pass by Value
n Default Mechanism For Passing Parameters:
l Parameter value is copied
l Variable can be changed inside the method
l Has no effect on value outside the method
l Parameter must be of the same type or compatible type
static void AddOne(int x)
{
x++; // Increment x
}
static void Main( )
{
int k = 6;
AddOne(k);
Console.WriteLine(k); // Display the value 6, not 7
}
static void AddOne(int x)
{
x++; // Increment x
}
static void Main( )
{
int k = 6;
AddOne(k);
Console.WriteLine(k); // Display the value 6, not 7
}
In most applications, most parameters are used for passing information into a
method but not out. Therefore, pass by value is the default mechanism for
passing parameters in C#.
Defining Value Parameters
The simplest definition of a parameter is a type name followed by a variable
name. This is known as a value parameter. When the method is called, a new
storage location is created for each value parameter, and the values of the
corresponding expressions are copied into them.
The expression supplied for each value parameter must be the same type as the
declaration of the value parameter, or a type that can be implicitly converted to
that type. Within the method, you can write code that changes the value of the
parameter. It will have no effect on any variables outside the method call.
In the following example, the variable x inside AddOne is completely separate
from the variable k in Main. The variable x can be changed in AddOne, but
this has no effect on k.
static void AddOne(int x)
{
x++;
}
static void Main( )
{
int k = 6;
AddOne(k);
Console.WriteLine(k); // Display the value 6, not 7
}
Module 5: Methods and Parameters 21
Pass by Reference
n What Are Reference Parameters?
l A reference to memory location
n Using Reference Parameters
l Use the ref keyword in method declaration and call
l Match types and variable values
l Changes made in the method affect the caller
l Assign parameter value before calling the method
What Are Reference Parameters?
A reference parameter is a reference to a memory location. Unlike a value
parameter, a reference parameter does not create a new storage location. Instead,
a reference parameter represents the same location in memory as the variable
that is supplied in the method call.
Declaring Reference Parameters
You can declare a reference parameter by using the ref keyword before the type
name, as shown in the following example:
static void ShowReference(ref int nVar, ref long nCount)
{
// ...
}
Using Multiple Parameter Types
The ref keyword only applies to the parameter following it, not to the whole
parameter list. Consider the following method, in which refVar is passed by
reference but longVar is passed by value:
static void OneRefOneVal(ref int refVar, long longVar)
{
// ...
}

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
47#
 楼主| 发表于 2006-8-13 21:17 | 只看该作者
22 Module 5: Methods and Parameters
Matching Parameter Types and Values
When calling the method, you supply reference parameters by using the ref
keyword followed by a variable. The value supplied in the call to the method
must exactly match the type in the method definition, and it must be a variable,
not a constant or calculated expression.
int x;
long q;
ShowReference(ref x, ref q);
If you omit the ref keyword, or if you supply a constant or calculated
expression, the compiler will reject the call, and you will receive an error
message similar to the following: “Cannot convert from ‘int’ to ‘ref int.’”
Changing Reference Parameter Values
If you change the value of a reference parameter, the variable supplied by the
caller is also changed, because they are both references to the same location in
memory. The following example shows how changing the reference parameter
also changes the variable:
static void AddOne(ref int x)
{
x++;
}
static void Main( )
{
int k = 6;
AddOne(ref k);
Console.WriteLine(k); // Display the value 7
}
This works because when AddOne is called, its parameter x is set up to refer to
the same memory location as the variable k in Main. Therefore, incrementing x
will increment k.
Module 5: Methods and Parameters 23
Assigning Parameters Before Calling the Method
A ref parameter must be definitively assigned at the point of call; that is, the
compiler must ensure that a value is assigned before the call is made. The
following example shows how you can initialize reference parameters before
calling the method:
static void AddOne(ref int x)
{
x++;
}
static void Main( )
{
int k = 6;
AddOne(ref k);
Console.WriteLine(k); // 7
}
The following example shows what happens if a reference parameter k is not
initialized before its method AddOne is called:
int k;
AddOne(ref k);
Console.WriteLine(k);
The C# compiler will reject this code and display the following error message:
“Use of unassigned local variable ‘k.’”
24 Module 5: Methods and Parameters
Output Parameters
n What Are Output Parameters?
l Values are passed out but not in
n Using Output Parameters
l Like ref, but values are not passed into the method
l Use out keyword in method declaration and call
static void OutDemo(out int p)
{
// ...
}
int n;
OutDemo(out n);
static void OutDemo(out int p)
{
// ...
}
int n;
OutDemo(out n);
What Are Output Parameters?
Output parameters are like reference parameters, except that they transfer data
out of the method rather than into it. They are similar to reference parameters.
Like a reference parameter, an output parameter is a reference to a storage
location supplied by the caller. However, the variable that is supplied for the
out parameter does not need to be assigned a value before the call is made, and
the method will assume that the parameter has not been initialized on entry.
Output parameters are useful when you want to be able to return values from a
method by means of a parameter without assigning an initial value to the
parameter.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
48#
 楼主| 发表于 2006-8-13 21:17 | 只看该作者
r a limited form of protection against unintended
modification of parameter values, because any changes that are made inside the
method have no effect outside it. This suggests that you should use value
parameters unless you need to pass information out of a method.
If you need to pass data out of a method, you can use the return statement,
reference parameters, or output parameters. The return statement is easy to use,
but it can only return one result. If you need multiple values returned, you must
use the reference and output parameter types. Use ref if you need to transfer
data in both directions, and use out if you only need to transfer data out of the
method.
Efficiency
Generally, simple types such as int and long are most efficiently passed by
value.
These efficiency concerns are not built into the language, and you should not
rely on them. Although efficiency is sometimes a consideration in large,
resource-intensive applications, it is usually better to consider program
correctness, stability, and robustness before efficiency. Make good
programming practices a higher priority than efficiency.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
49#
 楼主| 发表于 2006-8-13 21:18 | 只看该作者
Module 5: Methods and Parameters 25
Using Output Parameters
To declare an output parameter, use the keyword out before the type and name,
as shown in the following example:
static void OutDemo(out int p)
{
// ...
}
As with the ref keyword, the out keyword only affects one parameter, and each
out parameter must be marked separately.
When calling a method with an out parameter, place the out keyword before
the variable to be passed, as in the following example.
int n;
OutDemo(out n);
In the body of the method being called, no initial assumptions are made about
the contents of the output parameter. It is treated just like an unassigned local
variable.
26 Module 5: Methods and Parameters
Using Variable-Length Parameter Lists
n Use the params Keyword
n Declare As an Array at the End of the Parameter List
n Always Pass by Value
static long AddList(params long[ ] v)
{
long total, i;
for (i = 0, total = 0; i < v.Length; i++)
total += v;
return total;
}
static void Main( )
{
long x = AddList(63,21,84);
}
static long AddList(params long[ ] v)
{
long total, i;
for (i = 0, total = 0; i < v.Length; i++)
total += v;
return total;
}
static void Main( )
{
long x = AddList(63,21,84);
}
C# provides a mechanism for passing variable- length parameter lists.
Declaring Variable-Length Parameters
It is sometimes useful to have a method that can accept a varying number of
parameters. In C#, you can use the params keyword to specify a variablelength
parameter list. When you declare a variable - length parameter, you must:
n Declare only one params parameter per method.
n Place the parameter at the end of the parameter list.
n Declare the parameter as a single-dimension array type.
The following example shows how to declare a variable-length parameter list:
static long AddList(params long[ ] v)
{
long total;
long i;
for (i = 0, total = 0; i < v. Length; i++)
total += v;
return total;
}
Because a params parameter is always an array, all values must be the same
type.
Module 5: Methods and Parameters 27
Passing Values
When you call a method with a variable-length parameter, you can pass values
to the params parameter in one of two ways:
n As a list of elements (the list can be empty)
n As an array
The following code shows both techniques. The two techniques are treated in
exactly the same way by the compiler.
static void Main( )
{
long x;
x = AddList(63,21,84); // List
x = AddList(new long[ ]{ 63, 21, 84 }); // Array
}
Regardless of which method you use to call the method, the params parameter
is treated like an array. You can use the Length property of the array to
determine how many parameters were passed to each call.
In a params parameter, a copy of the data is made, and although you can
modify the values inside the method, the values outside the method are
unchanged.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
50#
 楼主| 发表于 2006-8-13 21:18 | 只看该作者
28 Module 5: Methods and Parameters
Guidelines for Passing Parameters
n Mechanisms
l Pass by value is most common
l Method return value is useful for single values
l Use ref and/or out for multiple return values
l Only use ref if data is transferred both ways
n Efficiency
l Pass by value is generally the most efficient
With so many options available for parameter passing, the most appropriate
choice might not be obvious. Two factors for you to consider when you choose
a way to pass parameters are the mechanism and its efficiency.
Mechanisms
Value parameters offe
Module 5: Methods and Parameters 29
Using Recursive Methods
n A Method Can Call Itself
l Directly
l Indirectly
n Useful for Solving Certain Problems
n Example
A method can call itself. This technique is known as recursion. You can
address some types of problems with recursive solutions. Recursive methods
are often useful when manipulating more complex data structures such as lists
and trees.
Methods in C# can be mutually recursive. For example, a situation in which
method A can call method B, and method B can call method A, is allowable.
Example of a Recursive Method
The Fibonacci sequence occurs in several situations in mathematics and biology
(for example, the reproductive rate and population of rabbits). The nth member
of this sequence has the value 1 if n is 1 or 2; otherwise, it is equal to the sum of
the preceding two numbers in the sequence. Notice that when n is greater than
two the value of the nth member of the sequence is derived from the values of
two previous values of the sequence. When the definition of a method refers to
the method itself, recursion might be involved.
You can implement the Fibonacci method as follows:
static ulong Fibonacci(ulong n)
{
if (n <= 2)
return 1;
else
return Fibonacci(n-1) + Fibonacci(n-2);
}
Notice that two calls are made to the method from within the method itself.
A recursive method must have a terminating condition that ensures that it will
return without making further calls. In the case of the Fibonacci method, the
test for n <= 2 is the terminating condition.
30 Module 5: Methods and Parameters
u Using Overloaded Methods
n Declaring Overloaded Methods
n Method Signatures
n Using Overloaded Methods
Methods might not have the same name as other non-method items in a class.
However, it is possible for two or more methods in a class to share the same
name. Name sharing among methods is called overloading.
In this section, you will learn:
n How to declare overloaded methods.
n How C# uses signatures to distinguish methods that have the same name.
n When to use overloaded methods.
Module 5: Methods and Parameters 31
Declaring Overloaded Methods
n Methods That Share a Name in a Class
l Distinguished by examining parameter lists
class OverloadingExample
{
static int Add(int a, int b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static void Main( )
{
Console.WriteLine(Add(1,2) + Add(1,2,3));
}
}
class OverloadingExample
{
static int Add(int a, int b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static void Main( )
{
Console.WriteLine(Add(1,2) + Add(1,2,3));
}
}
Overloaded methods are methods in a single class that have the same name. The
C# compiler distinguishes overloaded methods by comparing the parameter
lists.
Examples of Overloaded Methods
The following code shows how you can use different methods with the same
name in one class:
class OverloadingExample
{
static int Add(int a, int b)
{
return a + b;
}
static int Add(int a, int b, int c)
{
return a + b + c;
}
static void Main( )
{
Console.WriteLine(Add(1,2) + Add(3,4,5));
}
}

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

TOP技术积分榜 社区积分榜 徽章 团队 统计 知识索引树 积分竞拍 文本模式 帮助
  ITPUB首页 | ITPUB论坛 | 数据库技术 | 企业信息化 | 开发技术 | 微软技术 | 软件工程与项目管理 | IBM技术园地 | 行业纵向讨论 | IT招聘 | IT文档
  ChinaUnix | ChinaUnix博客 | ChinaUnix论坛
CopyRight 1999-2011 itpub.net All Right Reserved. 北京盛拓优讯信息技术有限公司版权所有 联系我们 未成年人举报专区 
京ICP备16024965号-8  北京市公安局海淀分局网监中心备案编号:11010802021510 广播电视节目制作经营许可证:编号(京)字第1149号
  
快速回复 返回顶部 返回列表