2012-03-20 54 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