2011-08-10 40 views
2

由於某種原因,我的字符串:「firstline」沒有被另一種方法拾取。這背後的推理是什麼?字符串在當前上下文中不存在 - C#

public static void test1() 
{ 
.. 
      string[] linesw = obj1.ReadToEnd().Split(new char[] { '\n' }); 
      string firstline = linesw[1]; 
.. 
} 

public static void test2() 
{ 
.. 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline); 
.. 
} 
+1

這是一個法律問題。爲什麼-1沒有解釋? –

回答

2

firstline是一個局部變量,並在不同的方法使用時,超出範圍。改爲將其作爲類變量或作爲參數提升。

作爲類變量:

private static string firstline = String.Empty; // class variable 

public static void test1() 
{ 
.. 
    string[] linesw = obj1.ReadToEnd().Split(new char[] { '\n' }); 
    firstline = linesw[1]; 
.. 
} 

public static void test2() 
{ 
.. 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline); 
.. 
} 

或者,作爲參數從test1()調用test2()時:

public static void test1() 
{ 
.. 
    string[] linesw = obj1.ReadToEnd().Split(new char[] { '\n' }); 
    string firstline = linesw[1]; 
    test2(firstline); 
.. 
} 

public static void test2(string firstline)... 
1

您正在創建本地變量,而不是僅僅分配給你已有的全局變量:

string[] linesw = obj1.ReadToEnd().Split(new char[] { '\n' }); 
firstline = linesw[1]; 
0

在C#中,當你在一個方法定義一個變量,你只能訪問它在定義方法中。換言之一個變量的範圍是例如定義塊:

private void test() 
    { 


    int i = 0; 
     //defining sub block 
     { 
      i++; // i is accessible in sub blocks. 
      int j = 0; 
     } 
    //ERROR : j is defined in the sub block, sub block is finished so it's out of scope 
     j++; 

    } 

您溶液處於較高範圍的水平來定義變量。像在課堂上一樣 你必須明確地將你的變量定義爲static。

private static string firstline; 
相關問題