Csharp/CSharp Tutorial/Language Basics/out
Содержание
Out Parameters
<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;
} class MainClass {
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>
myPoint(10, 15)
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;
} class MainClass {
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>
myPoint(10, 15)
Use out
<source lang="csharp">using System;
class Decompose {
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 }
}
class MainClass {
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>
Integer portion is 10 Fractional part is 0.125
Use "out" keyword (no need to assign because it is an out)
- An out parameter is used to pass a value out of a method.
- It is not necessary to give the variable used as an out parameter an initial value.
- An out parameter is always considered unassigned.
- The method must assign the parameter a value prior to the method"s termination.
<source lang="csharp">using System;
class MainClass
{
public static void Add(int x,int y, out int ans) { ans = x + y; } public static void Main() { Console.WriteLine("Adding 2 ints using out keyword"); int ans; Add(90, 90, out ans); Console.WriteLine("90 + 90 = {0}\n", ans); }
}</source>
Adding 2 ints using out keyword 90 + 90 = 180
Use two out parameters
<source lang="csharp">using System;
class Num {
public bool hasComFactor(int x, int y,out int least, out int greatest) { least = 1; greatest = 1; if(least != 1) return true; else return false; }
}
class MainClass {
public static void Main() { Num ob = new Num(); int lcf, gcf; if(ob.hasComFactor(231, 105, out lcf, out gcf)) { Console.WriteLine("Lcf of 231 and 105 is " + lcf); Console.WriteLine("Gcf of 231 and 105 is " + gcf); } else Console.WriteLine("No common factor for 35 and 49."); if(ob.hasComFactor(35, 51, out lcf, out gcf)) { Console.WriteLine("Lcf of 35 and 51 " + lcf); Console.WriteLine("Gcf of 35 and 51 is " + gcf); } else Console.WriteLine("No common factor for 35 and 51."); }
}</source>
No common factor for 35 and 49. No common factor for 35 and 51.