【问题标题】:CS0120 An object reference is required for the non-static field, method, or propertyCS0120 非静态字段、方法或属性需要对象引用
【发布时间】:2019-06-22 19:24:55
【问题描述】:

我正在尝试测试有人帮助我的重定向代码,它给了我两个 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
        }
    }
}
}

【问题讨论】:

    标签: c#


    【解决方案1】:

    如果您检查出现错误的两行,则您正在访问静态方法中的实例对象。这是错误的原因。

    在下面几行中,instId 是一个非静态变量,txtConsole 对象也是如此,这两个对象都是从静态方法访问的

     var processId = instId; //CS0120
    
     txtConsole.Text = r1; //CS0120
    

    【讨论】:

      【解决方案2】:

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

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

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

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

      如果您需要更多示例,请告诉我,我会进行编辑。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多