Csharp/C Sharp/Language Basics/Parameters Passing
Содержание
- 1 C# Ref and Out Parameters
- 2 Demonstrate params
- 3 Illustrates the use of out parameters
- 4 Objects are passed by reference
- 5 Objects can be passed to methods
- 6 Parameter demo
- 7 Parameter out and reference
- 8 Passing parameters by reference
- 9 Passing parameters by value
- 10 Passing Parameters By Value and By Ref
- 11 Pass value by reference
- 12 Pass value by reference with read only value
- 13 Ref and Out Parameters 2
- 14 Ref and Out Parameters: compiling error
- 15 Simple types are passed by value
- 16 Swap two references
- 17 Swap two values
- 18 Use out
- 19 Use ref to pass a value type by reference
- 20 Use regular parameter with a params parameter
- 21 Use two out parameters
C# Ref and Out Parameters
<source lang="csharp"> using System; class Point {
public Point(int x, int y) { this.x = x; this.y = y; } public void GetPoint(ref int x, ref int y) { x = this.x; y = this.y; } int x; int y;
} public class RefOutParameters2 {
public static void Main() { Point myPoint = new Point(10, 15); int x = 0; int y = 0; myPoint.GetPoint(ref x, ref y); Console.WriteLine("myPoint({0}, {1})", x, y); }
}
</source>
Demonstrate params
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Demonstrate params.
using System;
class Min {
public int minVal(params int[] nums) { int m; if(nums.Length == 0) { Console.WriteLine("Error: no arguments."); return 0; } m = nums[0]; for(int i=1; i < nums.Length; i++) if(nums[i] < m) m = nums[i]; return m; }
}
public class ParamsDemo {
public static void Main() { Min ob = new Min(); int min; int a = 10, b = 20; // call with two values min = ob.minVal(a, b); Console.WriteLine("Minimum is " + min); // call with 3 values min = ob.minVal(a, b, -1); Console.WriteLine("Minimum is " + min); // call with 5 values min = ob.minVal(18, 23, 3, 14, 25); Console.WriteLine("Minimum is " + min); // can call with an int array, too int[] args = { 45, 67, 34, 9, 112, 8 }; min = ob.minVal(args); Console.WriteLine("Minimum is " + min); }
}
</source>
Illustrates the use of out parameters
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example5_8.cs illustrates the use of out parameters
- /
// declare the MyMath class class MyMath {
// the SinAndCos() method returns the sin and cos values for // a given angle (in radians) public void SinAndCos(double angle, out double sin, out double cos) { sin = System.Math.Sin(angle); cos = System.Math.Cos(angle); }
}
public class Example5_8 {
public static void Main() { // declare and set the angle in radians double angle = System.Math.PI / 2; // declare the variables that will be used as out paramters double sin; double cos; // create a MyMath object MyMath myMath = new MyMath(); // get the sin and cos values from the SinAndCos() method myMath.SinAndCos(angle, out sin, out cos); // display sin and cos System.Console.WriteLine("sin = " + sin + ", cos = " + cos); }
}
</source>
Objects are passed by reference
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Objects are passed by reference.
using System;
class Test {
public int a, b; public Test(int i, int j) { a = i; b = j; } /* Pass an object. Now, ob.a and ob.b in object used in the call will be changed. */ public void change(Test ob) { ob.a = ob.a + ob.b; ob.b = -ob.b; }
}
public class CallByRef {
public static void Main() { Test ob = new Test(15, 20); Console.WriteLine("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.change(ob); Console.WriteLine("ob.a and ob.b after call: " + ob.a + " " + ob.b); }
}
</source>
Objects can be passed to methods
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Objects can be passed to methods.
using System;
class MyClass {
int alpha, beta; public MyClass(int i, int j) { alpha = i; beta = j; } /* Return true if ob contains the same values as the invoking object. */ public bool sameAs(MyClass ob) { if((ob.alpha == alpha) & (ob.beta == beta)) return true; else return false; } // Make a copy of ob. public void copy(MyClass ob) { alpha = ob.alpha; beta = ob.beta; } public void show() { Console.WriteLine("alpha: {0}, beta: {1}", alpha, beta); }
}
public class PassOb {
public static void Main() { MyClass ob1 = new MyClass(4, 5); MyClass ob2 = new MyClass(6, 7); Console.Write("ob1: "); ob1.show(); Console.Write("ob2: "); ob2.show(); if(ob1.sameAs(ob2)) Console.WriteLine("ob1 and ob2 have the same values."); else Console.WriteLine("ob1 and ob2 have different values."); Console.WriteLine(); // now, make ob1 a copy of ob2 ob1.copy(ob2); Console.Write("ob1 after copy: "); ob1.show(); if(ob1.sameAs(ob2)) Console.WriteLine("ob1 and ob2 have the same values."); else Console.WriteLine("ob1 and ob2 have different values."); }
}
</source>
Parameter demo
<source lang="csharp"> /* Learning C# by Jesse Liberty Publisher: O"Reilly ISBN: 0596003765
- /
using System; namespace ParamsDemo { public class TesterParamsDemo { public void Run() { int a = 5; int b = 6; int c = 7; Console.WriteLine("Calling with three integers"); DisplayVals(a,b,c); Console.WriteLine("\nCalling with four integers"); DisplayVals(5,6,7,8); Console.WriteLine("\ncalling with an array of four integers"); int [] explicitArray = new int[4] {5,6,7,8}; DisplayVals(explicitArray); } // takes a variable number of integers public void DisplayVals(params int[] intVals) { foreach (int i in intVals) { Console.WriteLine("DisplayVals {0}",i); } } [STAThread] static void Main() { TesterParamsDemo t = new TesterParamsDemo(); t.Run(); } } } </source>
Parameter out and reference
<source lang="csharp"> using System;
class ReferenceAndOutputParamtersTest {
static void Main( string[] args ) { int y = 5; int z; Console.WriteLine( "Original value of y: {0}", y ); Console.WriteLine( "Original value of z: uninitialized\n" ); SquareRef( ref y ); // must use keyword ref SquareOut( out z ); // must use keyword out Console.WriteLine( "Value of y after SquareRef: {0}", y ); Console.WriteLine( "Value of z after SquareOut: {0}\n", z ); Square( y ); Square( z ); Console.WriteLine( "Value of y after Square: {0}", y ); Console.WriteLine( "Value of z after Square: {0}", z ); } static void SquareRef( ref int x ) { x = x * x; } static void SquareOut( out int x ) { x = 6; x = x * x; } static void Square( int x ) { x = x * x; }
}
</source>
Passing parameters by reference
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example5_7.cs illustrates passing parameters by reference
- /
// declare the Swapper class class Swapper {
// the Swap() method swaps parameters passed by reference public void Swap(ref int x, ref int y) { // display the initial values System.Console.WriteLine("In Swap(): initial x = " + x + ", y = " + y); // swap x and y int temp = x; x = y; y = temp; // display the final values System.Console.WriteLine("In Swap(): final x = " + x + ", y = " + y); }
}
public class Example5_7 {
public static void Main() { // declare x and y (the variables whose values // are to be swapped) int x = 2; int y = 5; // display the initial values System.Console.WriteLine("In Main(): initial x = " + x + ", y = " + y); // create a Swapper object Swapper mySwapper = new Swapper(); // swap the values, passing a reference to the Swap() method mySwapper.Swap(ref x, ref y); // display the final values System.Console.WriteLine("In Main(): final x = " + x + ", y = " + y); }
}
</source>
Passing parameters by value
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example5_6.cs illustrates passing parameters by value
- /
// declare the Swapper class class Swapper {
// the Swap() method swaps parameters passed by value public void Swap(int x, int y) { // display the initial values System.Console.WriteLine("In Swap(): initial x = " + x + ", y = " + y); // swap x and y int temp = x; x = y; y = temp; // display the final values System.Console.WriteLine("In Swap(): final x = " + x + ", y = " + y); }
}
public class Example5_6 {
public static void Main() { // declare x and y (the variables whose values // are to be swapped) int x = 2; int y = 5; // display the initial values System.Console.WriteLine("In Main(): initial x = " + x + ", y = " + y); // create a Swapper object Swapper mySwapper = new Swapper(); // swap the values in x and y mySwapper.Swap(x, y); // display the final values System.Console.WriteLine("In Main(): final x = " + x + ", y = " + y); }
}
</source>
Passing Parameters By Value and By Ref
<source lang="csharp"> /*
* C# Programmers Pocket Consultant * Author: Gregory S. MacBeth * Email: gmacbeth@comporium.net * Create Date: June 27, 2003 * Last Modified Date: */
using System; namespace Client.Chapter_5___Building_Your_Own_Classes {
public class PassingParametersByValueandByRef { static void Main(string[] args) { int MyInt = 5; MyIntArray = new int[10]; ObjectCount++; Method2(); Method2(1, 2); MyMethodRef(ref MyInt); Method2(new int[] { 1, 2, 3, 4 }); } static private int MyInt = 5; static public int MyInt2 = 10; static public int[] MyIntArray; private static int ObjectCount = 0; static public int MyMethodRef(ref int myInt) { MyInt = MyInt + myInt; return MyInt; } static public int MyMethod(int myInt) { MyInt = MyInt + myInt; return MyInt; } static private long MyLongMethod(ref int myInt) { return myInt; } static public void Method2(params int[] args) { for (int I = 0; I < args.Length; I++) Console.WriteLine(args[I]); } }
}
</source>
Pass value by reference
<source lang="csharp"> /* Learning C# by Jesse Liberty Publisher: O"Reilly ISBN: 0596003765
- /
using System; namespace PassByRef { public class Time3 { // private member variables private int Year; private int Month; private int Date; private int Hour; private int Minute; private int Second; // Property (read only) public int GetHour() { return Hour; } // public accessor methods public void DisplayCurrentTime() { System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second); } public void GetTime(int h, int m, int s) { h = Hour; m = Minute; s = Second; } // constructor public Time3(System.DateTime dt) { Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; }
} public class PassByRefTester { public void Run() { System.DateTime currentTime = System.DateTime.Now; Time3 t = new Time3(currentTime); t.DisplayCurrentTime(); int theHour = 0; int theMinute = 0; int theSecond = 0; t.GetTime(theHour, theMinute, theSecond); System.Console.WriteLine("Current time: {0}:{1}:{2}", theHour, theMinute, theSecond); } static void Main() { PassByRefTester t = new PassByRefTester(); t.Run(); } } } </source>
Pass value by reference with read only value
<source lang="csharp"> /* Learning C# by Jesse Liberty Publisher: O"Reilly ISBN: 0596003765
- /
using System; namespace PassByRef { public class Time { // private member variables private int Year; private int Month; private int Date; private int Hour; private int Minute; private int Second; // Property (read only) public int GetHour() { return Hour; } // public accessor methods public void DisplayCurrentTime() { System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second); } // takes references to ints public void GetTime(ref int h, ref int m, ref int s) { h = Hour; m = Minute; s = Second; } // constructor public Time(System.DateTime dt) { Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; }
} public class TesterPassByRef { public void Run() { System.DateTime currentTime = System.DateTime.Now; Time t = new Time(currentTime); t.DisplayCurrentTime(); int theHour = 0; int theMinute = 0; int theSecond = 0; // pass the ints by reference t.GetTime(ref theHour, ref theMinute, ref theSecond); System.Console.WriteLine("Current time: {0}:{1}:{2}", theHour, theMinute, theSecond); } static void Main() { TesterPassByRef t = new TesterPassByRef(); t.Run(); } } } </source>
Ref and Out Parameters 2
<source lang="csharp"> using System; class Point {
public Point(int x, int y) { this.x = x; this.y = y; } public void GetPoint(out int x, out int y) { x = this.x; y = this.y; } int x; int y;
} public class RefOutParameters3 {
public static void Main() { Point myPoint = new Point(10, 15); int x; int y; myPoint.GetPoint(out x, out y); Console.WriteLine("myPoint({0}, {1})", x, y); }
}
</source>
Ref and Out Parameters: compiling error
<source lang="csharp"> // error using System; class Point {
public Point(int x, int y) { this.x = x; this.y = y; } // get both values in one function call public void GetPoint(ref int x, ref int y) { x = this.x; y = this.y; } int x; int y;
} public class RefOutParameters {
public static void Main() { Point myPoint = new Point(10, 15); int x; int y; // illegal myPoint.GetPoint(ref x, ref y); Console.WriteLine("myPoint({0}, {1})", x, y); }
}
</source>
Simple types are passed by value
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Simple types are passed by value.
using System;
class Test {
/* This method causes no change to the arguments used in the call. */ public void noChange(int i, int j) { i = i + j; j = -j; }
}
public class CallByValue {
public static void Main() { Test ob = new Test(); int a = 15, b = 20; Console.WriteLine("a and b before call: " + a + " " + b); ob.noChange(a, b); Console.WriteLine("a and b after call: " + a + " " + b); }
}
</source>
Swap two references
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Swap two references.
using System;
class RefSwap {
int a, b; public RefSwap(int i, int j) { a = i; b = j; } public void show() { Console.WriteLine("a: {0}, b: {1}", a, b); } // This method now changes its arguments. public void swap(ref RefSwap ob1, ref RefSwap ob2) { RefSwap t; t = ob1; ob1 = ob2; ob2 = t; }
}
public class RefSwapDemo {
public static void Main() { RefSwap x = new RefSwap(1, 2); RefSwap y = new RefSwap(3, 4); Console.Write("x before call: "); x.show(); Console.Write("y before call: "); y.show(); Console.WriteLine(); // exchange the objects to which x and y refer x.swap(ref x, ref y); Console.Write("x after call: "); x.show(); Console.Write("y after call: "); y.show(); }
}
</source>
Swap two values
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Swap two values.
using System;
class Swap {
// This method now changes its arguments. public void swap(ref int a, ref int b) { int t; t = a; a = b; b = t; }
}
public class SwapDemo {
public static void Main() { Swap ob = new Swap(); int x = 10, y = 20; Console.WriteLine("x and y before call: " + x + " " + y); ob.swap(ref x, ref y); Console.WriteLine("x and y after call: " + x + " " + y); }
}
</source>
Use out
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Use out.
using System;
class Decompose {
/* Decompose a floating-point value into its integer and fractional parts. */ public int parts(double n, out double frac) { int whole; whole = (int) n; frac = n - whole; // pass fractional part back through frac return whole; // return integer portion }
}
public class UseOut {
public static void Main() { Decompose ob = new Decompose(); int i; double f; i = ob.parts(10.125, out f); Console.WriteLine("Integer portion is " + i); Console.WriteLine("Fractional part is " + f); }
}
</source>
Use ref to pass a value type by reference
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Use ref to pass a value type by reference.
using System;
class RefTest {
/* This method changes its arguments. Notice the use of ref. */ public void sqr(ref int i) { i = i * i; }
}
public class RefDemo {
public static void Main() { RefTest ob = new RefTest(); int a = 10; Console.WriteLine("a before call: " + a); ob.sqr(ref a); // notice the use of ref Console.WriteLine("a after call: " + a); }
}
</source>
Use regular parameter with a params parameter
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Use regular parameter with a params parameter.
using System;
class MyClass {
public void showArgs(string msg, params int[] nums) { Console.Write(msg + ": "); foreach(int i in nums) Console.Write(i + " "); Console.WriteLine(); }
}
public class ParamsDemo2 {
public static void Main() { MyClass ob = new MyClass(); ob.showArgs("Here are some integers", 1, 2, 3, 4, 5); ob.showArgs("Here are two more", 17, 20); }
}
</source>
Use two out parameters
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Use two out parameters.
using System;
class Num {
/* Determine if x and v have a common denominator. If so, return least and greatest common denominators in the out parameters. */ public bool isComDenom(int x, int y, out int least, out int greatest) { int i; int max = x < y ? x : y; bool first = true; least = 1; greatest = 1; // find least and treatest common denominators for(i=2; i <= max/2 + 1; i++) { if( ((y%i)==0) & ((x%i)==0) ) { if(first) { least = i; first = false; } greatest = i; } } if(least != 1) return true; else return false; }
}
public class DemoOut {
public static void Main() { Num ob = new Num(); int lcd, gcd; if(ob.isComDenom(231, 105, out lcd, out gcd)) { Console.WriteLine("Lcd of 231 and 105 is " + lcd); Console.WriteLine("Gcd of 231 and 105 is " + gcd); } else Console.WriteLine("No common denominator for 35 and 49."); if(ob.isComDenom(35, 51, out lcd, out gcd)) { Console.WriteLine("Lcd of 35 and 51 " + lcd); Console.WriteLine("Gcd of 35 and 51 is " + gcd); } else Console.WriteLine("No common denominator for 35 and 51."); }
}
</source>