我正在学习C#,但是我不太理解static
关键字。
假设我有以下代码:
using System;
using System.IO;
using System.IO.Ports;
class PortThing
{
SerialPort port;
void InitPort()
{
if(!File.Exists("/dev/whatever"))
{
System.Console.WriteLine("Device not found.");
port = null;
}
//else port = something
}
public static void Main(string[] args)
{
InitPort();
System.Console.WriteLine("Done.");
}
}
据我所理解,静态方法属于类而不是该类的对象。因此,静态方法不能引用非静态方法/字段,因为它们需要实例化一个类。
编译器抱怨
Main()
调用 InitPort()
并希望将其变为静态方法。 我可以这样做,但这需要使 port
成为静态字段。按照这种思路,一切都会变成静态。我哪里理解错了?