我正在学习C#,并且无法理解static
关键字。了解C#中的静态内容#
说我有以下代码:
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
成为一个静态字段。遵循这一思路,一切都将最终成为静态的。
我得到什么错误?
所有静态成员...不只是静态字段 – 2010-12-22 13:06:36