我知道之前已经有人问过这个问题,但是那些场景都太具体了,我对基础概念感到困惑。
我有两个基本版本的C#程序,一个可以工作,另一个不行。如果有人能够解释一下为什么在第二个程序中会出现需要非静态字段、方法或属性的对象引用的错误,我会很感激。
可以工作的版本:
namespace Experiments
{
class Test
{
public string myTest = "Gobbledigook";
public void Print()
{
Console.Write(myTest);
}
}
class Program
{
static void Main(string[] args)
{
Test newTest = new Test();
newTest.Print();
while (true)
;
}
}
}
无法工作:
namespace Experiments
{
class Test
{
public string myTest = "Gobbledigook";
public void Print()
{
Console.Write(myTest);
}
}
class Program
{
public Test newTest = new Test();
static void Main(string[] args)
{
newTest.Print();
while (true)
;
}
}
}
当我尝试从第二个程序的Test()类打印文本时,它会给出错误需要对象引用来访问非静态字段、方法或属性,我不明白为什么会这样。我可以看到它与我声明Test()类的实例的位置有关,但我不记得在C++中发生过这样的事情,所以它让我感到困惑。
发生了什么?