Csharp/CSharp Tutorial/Class/Method Parameter

Материал из .Net Framework эксперт
Версия от 12:16, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A member function with two arguments

using System; 
 
class ChkNum {  
  public int sum(int a, int b) { 
    int max; 
    max = a < b ? a : b; 
 
    return max; 
  } 
}  
  
class MainClass {  
  public static void Main() {  
    ChkNum ob = new ChkNum(); 
    int a, b; 
 
    a = 7; 
    b = 8; 
    Console.WriteLine(ob.sum(a, b)); 
 
    a = 100; 
    b = 8; 
    Console.WriteLine(ob.sum(a, b)); 
 
    a = 100; 
    b = 75; 
    Console.WriteLine(ob.sum(a, b)); 
 
  }  
}
7
8
75

C# Parameter Modifiers

Parameter Modifier                           Meaning in Life
(none)                                       Assumed to be passed by value.
out                                          Output parameters are assigned. 
params                                       send in a variable number of arguments as a single logical parameter. 
ref                                          The value is initially assigned by the caller, and may be optionally reassigned by the called method.

Creating a method with a reference argument.

using System;
class MainClass {
    static void Main() {
        int x = 10;
        Console.WriteLine("Before calling non-ref function, x = {0}", x);
        NonRefFunction(x);
        Console.WriteLine("After calling non-ref function, x = {0}", x);
        RefFunction(ref x);
        Console.WriteLine("After calling ref function, x = {0}", x);
    }
    static void NonRefFunction(int x) {
        Console.WriteLine("Top of NonRefFunction. X = {0}", x);
        x = x + 10;
        Console.WriteLine("Bottom of NonRefFunction. X = {0}", x);
    }
    static void RefFunction(ref int x) {
        Console.WriteLine("Top of RefFunction. X = {0}", x);
        x = x + 10;
        Console.WriteLine("Bottom of RefFunction. X = {0}", x);
    }
}

How Arguments Are Passed

Call-by-value:

  1. Copy the value of an argument into the formal parameter.
  2. Change made to the parameter have no effect on the argument used in the call .

Call-by-reference.

  1. A reference to an argument is passed to the parameter.
  2. Change made to the parameter will affect the argument used to call the subroutine.

When you pass a value type, such as int or double, to a method, it is passed by value.

An object is passed by reference

7.6.Method Parameter 7.6.1. How Arguments Are Passed 7.6.2. <A href="/Tutorial/CSharp/0140__Class/Parametermodifiers.htm">Parameter modifiers</a> 7.6.3. <A href="/Tutorial/CSharp/0140__Class/Passintvaluetoafunction.htm">Pass int value to a function</a> 7.6.4. <A href="/Tutorial/CSharp/0140__Class/Useaparameterinamemberfunction.htm">Use a parameter in a member function</a> 7.6.5. <A href="/Tutorial/CSharp/0140__Class/Amemberfunctionwithtwoarguments.htm">A member function with two arguments</a> 7.6.6. <A href="/Tutorial/CSharp/0140__Class/Passintwithoutoutandref.htm">Pass int without "out" and "ref"</a> 7.6.7. <A href="/Tutorial/CSharp/0140__Class/Passintegerbyref.htm">Pass integer by ref</a> 7.6.8. <A href="/Tutorial/CSharp/0140__Class/refparameters.htm">ref parameters</a> 7.6.9. <A href="/Tutorial/CSharp/0140__Class/Passintegervaluebyvalue.htm">Pass integer value by value</a> 7.6.10. <A href="/Tutorial/CSharp/0140__Class/paramsintargs.htm">params int[] args</a> 7.6.11. <A href="/Tutorial/CSharp/0140__Class/Useoutforinttype.htm">Use out for int type</a> 7.6.12. <A href="/Tutorial/CSharp/0140__Class/Creatingamethodwithareferenceargument.htm">Creating a method with a reference argument.</a> 7.6.13. <A href="/Tutorial/CSharp/0140__Class/VariableargumentstoamethodinC.htm">Variable arguments to a method in C#.</a> 7.6.14. <A href="/Tutorial/CSharp/0140__Class/Methodparameterhidestheclassmemberfield.htm">Method parameter hides the class member field</a> 7.6.15. <A href="/Tutorial/CSharp/0140__Class/CParameterModifiers.htm">C# Parameter Modifiers</a> 7.6.16. <A href="/Tutorial/CSharp/0140__Class/useofoutervariableinanonymousmethod.htm">use of "outer variable" in anonymous method</a>

Method parameter hides the class member field

public class Product {
    public int yearBuilt;
    public double maximumSpeed;
    public int Age(int currentYear) {
        int maximumSpeed = 100;  // hides the field
        System.Console.WriteLine("In Age(): maximumSpeed = " + maximumSpeed);
        int age = currentYear - yearBuilt;
        return age;
    }
    public double Distance(double initialSpeed, double time) {
        System.Console.WriteLine("In Distance(): maximumSpeed = " + maximumSpeed);
        return (initialSpeed + maximumSpeed) / 2 * time;
    }
}

class MainClass{
    public static void Main() {
        Product redPorsche = new Product();
        redPorsche.yearBuilt = 2000;
        redPorsche.maximumSpeed = 150;
        int age = redPorsche.Age(2001);
        System.Console.WriteLine("redPorsche is " + age + " year old.");
        System.Console.WriteLine("redPorsche travels " + redPorsche.Distance(31, .25) + " miles.");
    }
}

Parameter modifiers

Parameter modifier      Passed by              Variable must be definitely assigned
None                  Value                  Going in
ref                     Reference              Going in
out                     Reference              Going out

params int[] args

using System;
class MainClass
{
  static void Main(string[] args)
  {
    MyMethod(5,5,5,5);
   
  }
  
  static public void MyMethod(params int[] args)
  {
    for (int I = 0; I < args.Length; I++)
      Console.WriteLine(args[I]);
  }
}
5
5
5
5

Pass integer by ref

using System;
class MainClass
{
  static void Main(string[] args)
  {
      int MyInt = 5;
    MyMethodRef(ref MyInt);
   
        Console.WriteLine(MyInt);
  }
  
  static public int MyMethodRef(ref int myInt)
  {
    myInt = myInt + myInt;
    return myInt;
  }
}
10

Pass integer value by value

using System;
class MainClass
{
  static void Main(string[] args)
  {
      int MyInt = 5;
    MyMethod( MyInt);
   
        Console.WriteLine(MyInt);
  }
  
  static public int MyMethod( int myInt)
  {
    myInt = myInt + myInt;
    return myInt;
  }
}
5

Pass int value to a function

using System;
class MainClass
{
   public static void Main() {
      int SomeInt = 6;
      
      int s = Sum(5, SomeInt);
      
      Console.WriteLine(s);        
   }
   public static int Sum(int x, int y)               // Declare the method.
   {
      return x + y;                                  // Return the sum.
   }
   
}
11

Pass int without "out" and "ref"

using System;
class MyClass
{
   public int Val = 20;
}
class MainClass
{
   static void MyMethod(MyClass myObject, int intValue)
   {
      myObject.Val = myObject.Val + 5;
      intValue = intValue + 5;        
   }
   static void Main()
   {
      MyClass myObject = new MyClass();
      int intValue = 10;
      Console.WriteLine("Before -- myObject.Val: {0}, intValue: {1}", myObject.Val, intValue);
      MyMethod(myObject, intValue);
      Console.WriteLine("After  -- myObject.Val: {0}, intValue: {1}", myObject.Val, intValue);
   }
}
Before -- myObject.Val: 20, intValue: 10
After  -- myObject.Val: 25, intValue: 10

ref parameters

using System;
class Color {
    public Color() {
        this.red = 0;
        this.green = 127;
        this.blue = 255;
    }
    protected int red;
    protected int green;
    protected int blue;
    public void GetRGB(
        ref int red, ref int green, ref int blue) {
        red = this.red;
        green = this.green;
        blue = this.blue;
    }
}
class Class1 {
    static void Main(string[] args) {
        Color c = new Color();
        int red = 1;
        int green = 2;
        int blue = 3;
        c.GetRGB(ref red, ref green, ref blue);
        Console.WriteLine("R={0}, G={1}, B={2}", red, green, blue);
    }
}

Use a parameter in a member function

using System; 
 
class ChkNum {  
  // Return true if x is prime. 
  public bool isPrime(int x) { 
    for(int i=2; i <= x/i; i++) 
      if((x %i) == 0) return false; 
 
    return true; 
  } 
}  
  
class MainClass {  
  public static void Main() {  
    ChkNum ob = new ChkNum(); 
 
    for(int i=1; i < 10; i++) 
      if(ob.isPrime(i)) Console.WriteLine(i + " is prime."); 
      else Console.WriteLine(i + " is not prime."); 
 
  }  
}
1 is prime.
2 is prime.
3 is prime.
4 is not prime.
5 is prime.
6 is not prime.
7 is prime.
8 is not prime.
9 is not prime.

use of "outer variable" in anonymous method

using System;
using System.Collections.Generic;
using System.Text;
    class Program
    {
        delegate void MessagePrintDelegate(string msg);
        static void Main(string[] args)
        {
            string source = "Outer";
            MessagePrintDelegate mpd3 = delegate(string msg)
            {
                Console.WriteLine("[{0}] {1}", source, msg);
            };
            LongRunningMethod(mpd3);
        }
        static void LongRunningMethod(MessagePrintDelegate mpd)
        {
            for (int i = 0; i < 99; i++)
            {
                if (i % 25 == 0)
                {
                    mpd(string.Format("Progress Made. {0}% complete.", i));
                }
            }
        }
        static void PrintMessage(string msg)
        {
            Console.WriteLine("[PrintMessage] {0}", msg);
        }
    }

Use out for int type

using System;
class MyClass
{
   public int Val = 20;                     
}
class MainClass
{
   static void MyMethod(out MyClass f1, out int f2)
   {
      f1 = new MyClass();                   
      f1.Val = 25;                          
      f2 = 15;                              
   }
   static void Main()
   {
      MyClass myObject = null;
      int intValue;
      MyMethod(out myObject, out intValue);             
      Console.WriteLine("After  -- myObject.Val: {0}, intValue: {1}", myObject.Val, intValue);
   }
}
After  -- myObject.Val: 25, intValue: 15

Variable arguments to a method in C#.

using System;
class MainClass {
    public static void PrintParams(params object[] list) {
        for (int i = 0; i < list.Length; ++i)
            Console.WriteLine("Object {0} = {1} ({2})", i, list[i], list[i].GetType());
    }
    public static void Main() {
        PrintParams(1, 2, "a", "b", 23.4);
    }
}