【程式設計】【C# – 變數的視野/scope】

在C# ,變數的視野/Scope是說變數的可見範圍、影響範圍…,共有三種scope:

  1. 類別/class
  2. 方法/method
  3. for, while and do while loop, if and switch敘述

類別視野範例:

class Test
{  // 類別視野的起始
 
  // 在類別中,宣告並初始化一個變數
    string colorName = "red";
 
  // 宣告一個方法 
    public void GetValue()            
    {
      /* 當一個變數是在類別中宣告的話,可以在這個類別中的任何地方被存取。*/
        Console.WriteLine(colorName); 
    }   // 方法的結束
 
} //類別視野結束

方法視野範例:

class Program
{      // 類別視野的起始
       public static void ShowVariable1()
       {  // 第一個方法視野的起始
 
           //宣告整數變數int,並給予初值100
           int number = 100;
 
           // 印出變數
           Console.WriteLine(number);
 
       }  // ShowVariable1 ()方法視野的結束
 
       public static void ShowVariable2()     // 第二個方法視野的起始
       {
         // 印出numver變數,但是,會產生編譯錯誤,因為,在這個方法中,無法存取另一個方法所宣告的變數number
           Console.WriteLine(number);                    
 
       } // ShowVariable2 ()方法視野的結束
   }

for, while and do while loop, if and switch statements 

class Program
    {  // 類別視野的起始
        static void Main(string[] args)         // main方法的起始
        {
            for (int i = 0; i <= 10; i++)
            {  // loop視野的起始
 
                //存取在for區塊中所宣告的變數i
                Console.WriteLine(i);
            }   // End for loop scope
 
            //在for區塊外面,存取for內部的變數i,這樣會造成編譯錯誤!
            Console.WriteLine(i);
            Console.ReadKey();
        }   // main方法視野的結束
    }   // 類別視野的結束

下面的程式中,ShowVariable1與ShowVariable2各印出多少?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static int number = 100;

        static void Main(string[] args)
        {
        }

        public static void ShowVariable1()
        {  // 第一個方法視野的起始

            //宣告整數變數int,並給予初值100


            // 印出變數
            int number = 200;
            Console.WriteLine(number);

        }  // ShowVariable1 ()方法視野的結束

        public static void ShowVariable2()     // 第二個方法視野的起始
        {
            // 印出numver變數,但是,會產生編譯錯誤,因為,在這個方法中,無法存取另一個方法所宣告的變數number
            Console.WriteLine(number);

        } // ShowVariable2 ()方法視野的結束
    }
}

 

延伸閱讀:

  1. Value Type and Reference Type
  2. Understanding Classes and Objects the C# Way

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料