2012-03-20 53 views
1
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 

namespace LearnThread 
{ 
    class Delay 
    { 
     public int timePass() 
     { 
      static int i=0; 
      for(i=0; i<100;i++) 
      { 
       Thread.Sleep(1000); 
      } 
      return i; 
     } 
    } 
} 

Error:The modifier 'static' is not valid for this item靜態INT

爲什麼靜態是錯誤嗎?我們不能在int語言中使用static,因爲我們可以在C語言中使用它?

+10

因爲C#是不是C. – leppie 2012-03-20 12:58:57

+0

你怎麼能指望一個實例方法的靜態局部變量_inside_表現? – David 2012-03-20 12:59:25

+0

另外,無論如何,「我」在那裏靜態有什麼意義? – Matthew 2012-03-20 13:18:50

回答

13

您無法將本地作用域變量聲明爲static,這正是您正在做的事情。

您可以爲類(即它是類的成員)創建一個靜態字段或靜態屬性,該類將駐留在方法的以外的

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

namespace LearnThread 
{ 
    class Delay 
    { 
     static int i=0; 

     public int timePass() 
     { 
      for(i=0; i<100;i++) 
      { 
       Thread.Sleep(1000); 
      } 
      return i; 
     } 
    } 
} 

雖然,這個代碼似乎有點啞......爲什麼還要使用一個for循環迭代靜態字段?多次調用該方法可能會導致很多問題。我認爲你要麼通過瘋狂的代碼來學習C#,要麼試圖解決另一個問題,並將這些代碼扔進去。無論是或者......你做錯了。 :)

+0

謝謝分配。我在學。 :) – SHRI 2012-03-20 13:08:34

1

你不能在裏面定義靜態變量function,只能在class級別。

1

在方法內部不能有靜態變量,因爲當從方法體返回時它會超出範圍。將其移至課程級別,並且靜態整數可用。

+0

謝謝分配:) – SHRI 2012-03-20 13:16:37

1

Static Variable:A field declared with the static modifier is called a static variable. A static variable comes into existence before execution of the static constructor.

To access a static variable, you must "qualify" where you want to use it. Qualifying a member means you must specify its class.

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

namespace LearnThread 
{ 
    class Delay 

    { 
     static int i=0; 

     public int timePass() 
     { 

      for(i=0; i<100;i++) 
      { 
       Thread.Sleep(1000); 
      } 
      return i; 
     } 
    } 
} 
+0

謝謝allot Praveen Jee :) – SHRI 2012-03-20 13:26:24