在方法的for循环中无法看到类中的对象

use*_*338 0 c# object

我的示例代码:

public partial class Service1 : ServiceBase
{
    object a = new object ();

    static void methodA()
    {
        string[] tests = {"test1","test2","test3"}
        foreach(string test in tests)
        {
            a.SetValue(""); //object a cannot be seen
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

无法看到对象.如何在for循环中使用对象?

hor*_*rgh 6

你的方法是static.您无法从静态方法访问非静态字段.考虑一下你的方法(或变量)是否应该是静态的

  1. 使用static关键字声明您的变量
  2. static从方法声明中删除关键字

这是静态(C#参考)