Csharp/CSharp Tutorial/Language Basics/Variable Scope

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

Block scope.

using System; 
 
class Example { 
  public static void Main() { 
    int x; // known to all code within Main() 
 
    x = 10; 
    if(x == 10) { // start new scope
      int y = 20; // known only to this block 
 
      // x and y both known here. 
      Console.WriteLine("x and y: " + x + " " + y); 
    } 
    // y = 100; // Error! y not known here  
 
    // x is still known here. 
    Console.WriteLine("x is " + x); 
  } 
}
x and y: 10 20
x is 10

Lifetime of a variable.

using System; 
 
class Example { 
  public static void Main() { 
    int x;  
 
    for(x = 0; x < 3; x++) { 
      int y = -1;  
      Console.WriteLine("y is initialized each time block is entered.");
      Console.WriteLine("y is always -1: " + y);
      y = 100;
      Console.WriteLine("y is now: " + y);
    } 
  } 
}
y is initialized each time block is entered.
y is always -1: -1
y is now: 100
y is initialized each time block is entered.
y is always -1: -1
y is now: 100
y is initialized each time block is entered.
y is always -1: -1
y is now: 100

The Scope and Lifetime of Variables

  1. A block is begun with an opening curly brace and ended by a closing curly brace.
  2. A block defines a declaration space, or scope.
  3. Each time you start a new block, you are creating a new scope.
  4. Variables are created when their scope is entered and destroyed when their scope is left.

1.10.Variable Scope 1.10.1. The Scope and Lifetime of Variables 1.10.2. <A href="/Tutorial/CSharp/0020__Language-Basics/Blockscope.htm">Block scope.</a> 1.10.3. <A href="/Tutorial/CSharp/0020__Language-Basics/Lifetimeofavariable.htm">Lifetime of a variable.</a>