从另一个 class 调用函数时出错:字段初始值设定项无法引用非静态字段、方法或 属性

error while calling function from another class: A field initializer cannot reference the non static field,method,or property

我在从 class Form1 调用 class USBDriveSerialNumber 的 public 方法 getSerialNumberFromDriveLetter 时遇到此错误。

Error : A field initializer cannot reference the non static field,method,or property.

我的代码

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        USBDriveSerialNumber usb = new USBDriveSerialNumber();
        string serial = usb.getSerialNumberFromDriveLetter("f:\");
       // Debug.WriteLine(serial);
   }

}

//USBDriveSerialNumber Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace WindowsFormsApplication2
{
    class USBDriveSerialNumber
    {
        string _serialNumber;
        string _driveLetter;

        public string getSerialNumberFromDriveLetter(string driveLetter)
        {
            this._driveLetter = driveLetter.ToUpper();

            if (!this._driveLetter.Contains(":"))
            {
                this._driveLetter += ":";
            }

            matchDriveLetterWithSerial();

            return this._serialNumber;
        }

        public void matchDriveLetterWithSerial()
        {

            string[] diskArray;
            string driveNumber;
            string driveLetter;

            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
            foreach (ManagementObject dm in searcher1.Get())
            {
                diskArray = null;
                driveLetter = getValueInQuotes(dm["Dependent"].ToString());
                diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
                driveNumber = diskArray[0].Remove(0, 6).Trim();
                if (driveLetter == this._driveLetter)
                {
                    /* This is where we get the drive serial */
                    ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
                    foreach (ManagementObject disk in disks.Get())
                    {

                        if (disk["Name"].ToString() == ("\\.\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB")
                        {
                            this._serialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
                        }
                    }
                }
            }
        }

        private string parseSerialFromDeviceID(string deviceId)
        {
            string[] splitDeviceId = deviceId.Split('\');
            string[] serialArray;
            string serial;
            int arrayLen = splitDeviceId.Length - 1;

            serialArray = splitDeviceId[arrayLen].Split('&');
            serial = serialArray[0];

            return serial;
        }

        private string getValueInQuotes(string inValue)
        {
            string parsedValue = "";

            int posFoundStart = 0;
            int posFoundEnd = 0;

            posFoundStart = inValue.IndexOf("\"");
            posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1);

            parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);

            return parsedValue;
        }
    }
}

您应该在构造函数中调用 getSerialNumberFromDriveLetter 方法或创建一个新方法

      public Form1()
      {
        InitializeComponent();
        USBDriveSerialNumber usb = new USBDriveSerialNumber();
        string serial = usb.getSerialNumberFromDriveLetter("f:\");
      }

您不能使用一个实例变量来初始化另一个实例变量,因为编译器可以重新排列这些变量。

改为

string serial = new USBDriveSerialNumber().getSerialNumberFromDriveLetter("f:\");

或使 USB 静态化

static USBDriveSerialNumber usb = new USBDriveSerialNumber();
string serial = usb.getSerialNumberFromDriveLetter("f:\");

或将设置序列移至构造函数

string serial;
public Form1()
{
      InitializeComponent();
      serial = usb.getSerialNumberFromDriveLetter("f:\");
}