CS0120非静态字段,方法或属性需要对象引用

时间:2019-01-29 15:56:50

标签: c#

我正在尝试测试有人帮助我的重定向代码,它给了我两个cs0120错误。第一个在整数变量上,第二个在文本框上。我一般都不熟悉编码,并且正在自学C#。如果有人可以向我解释此错误的含义以及为什么得到此错误,那将非常好,因为我没有发现任何错误,并且根据其他项目,我认为它是正确的。错误一直在底部,但我想为此保留其余代码,以便即使您可能不需要它,也可以看到整个图片。

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RedirectRunningTest
{
public partial class Test1 : Form
{
    int instId;

    [DllImport("kernel32.dll")]
    private extern static IntPtr GetStdHandle(int nStdHandle);

    [DllImport("kernel32.dll")]
    static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput,
      [Out] StringBuilder lpCharacter, uint nLength, COORD dwReadCoord,
      out uint lpNumberOfCharsRead);

    [DllImport("kernel32.dll")]
    static extern bool FreeConsole();
    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(int dwProcessId);

    [DllImport("kernel32.dll")]
    static extern bool GetConsoleScreenBufferInfo(
        IntPtr hConsoleOutput,
        out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
    );

    [StructLayout(LayoutKind.Sequential)]
    struct COORD
    {
        public short X;
        public short Y;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct CONSOLE_SCREEN_BUFFER_INFO
    {

        public COORD dwSize;
        public COORD dwCursorPosition;
        public short wAttributes;
        public SMALL_RECT srWindow;
        public COORD dwMaximumWindowSize;

    }

    [StructLayout(LayoutKind.Sequential)]
    struct SMALL_RECT
    {

        public short Left;
        public short Top;
        public short Right;
        public short Bottom;

    }

    const int STD_OUTPUT_HANDLE = -11;
    const Int64 INVALID_HANDLE_VALUE = -1;

    public Test1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bool started = false;
        var p = new Process();
        p.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";

        started = p.Start();

        instId = p.Id;
    }
    private static string ReadALineOfConsoleOutput(IntPtr stdout, ref short currentPosition)
    {

        if (stdout.ToInt32() == INVALID_HANDLE_VALUE)
            throw new Win32Exception();

        //Get Console Info
        if (!GetConsoleScreenBufferInfo(stdout, out CONSOLE_SCREEN_BUFFER_INFO outInfo))
            throw new Win32Exception();

        //Gets Console Output Line Size
        short lineSize = outInfo.dwSize.X;

        //Calculates Number of Lines to be read
        uint numberofLinesToRead = (uint)(outInfo.dwCursorPosition.Y - currentPosition);

        if (numberofLinesToRead < 1) return null;

        //total characters to be read
        uint nLength = (uint)lineSize * numberofLinesToRead;

        StringBuilder lpCharacter = new StringBuilder((int)nLength);

        // read from the first character of the first line (0, 0).
        COORD dwReadCoord;
        dwReadCoord.X = 0;
        dwReadCoord.Y = currentPosition;


        if (!ReadConsoleOutputCharacter(stdout, lpCharacter, nLength, dwReadCoord, out uint lpNumberOfCharsRead))
            throw new Win32Exception();

        currentPosition = outInfo.dwCursorPosition.Y;

        return lpCharacter.ToString();
    }

    public static async Task Main()
    {
        var processId = instId; //CS0120
        if (!FreeConsole()) return;
        if (!AttachConsole(processId)) return;

        IntPtr stdout = GetStdHandle(STD_OUTPUT_HANDLE);
        short currentPosition = 0;

        while (true)
        {
            var r1 = ReadALineOfConsoleOutput(stdout, ref currentPosition);
            if (r1 != null)
                txtConsole.Text = r1; //CS0120
        }
    }
}
}

2 个答案:

答案 0 :(得分:2)

如果同时检查出错误的两行,则说明您正在使用静态方法访问实例对象。这是错误的原因。

在以下几行中,instId是一个非静态变量,txtConsole对象也是一个非静态变量,这两个对象都可以通过“静态方法”进行访问

 var processId = instId; //CS0120

 txtConsole.Text = r1; //CS0120

答案 1 :(得分:1)

您从静态上下文访问实例变量。

您应该声明一个staic方法,该方法将实例作为可以使用的参数。

例如将Test1作为参数添加到静态函数中,并通过静态函数访问Test1的属性。

另一种方法是使用静态类为Test1定义扩展方法。

如果您需要更多示例,请告诉我。

另请参阅CS0120: An object reference is required for the nonstatic field, method, or property 'foo'