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

C# CS0120非静态字段、方法或属性需要对象引用,c#,C#,我试图测试一个重定向代码,有人正在帮助我,它给了我两个cs0120错误。第一个用于整数变量,第二个用于文本框。一般来说,我对编码还不熟悉,正在自学C。如果有人能向我解释这个错误的含义以及我为什么会得到它,那将是非常好的,因为我认为它没有任何错误,并且基于我所做的其他项目,它看起来是正确的。错误都在底部,但我想把我的代码的其余部分放在这里,这样你就有了整个画面,即使你可能不需要它 using System; using System.ComponentModel; using System.Dia

我试图测试一个重定向代码,有人正在帮助我,它给了我两个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
        }
    }
}
}
使用系统;
使用系统组件模型;
使用系统诊断;
使用System.Runtime.InteropServices;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
命名空间重定向运行测试
{
公共部分类Test1:Form
{
国际教育学院;
[DllImport(“kernel32.dll”)]
私有外部静态IntPtr GetStdHandle(intnstdhandle);
[DllImport(“kernel32.dll”)]
静态外部布尔读控制台输出字符(IntPtr hConsoleOutput,
[Out]StringBuilder lpCharacter、uint NLENGHT、COORD dwReadCoord、,
out uint lpNumberOfCharsRead);
[DllImport(“kernel32.dll”)]
静态外部bool FreeConsole();
[DllImport(“kernel32.dll”)]
静态外部布尔附件控制台(int dwProcessId);
[DllImport(“kernel32.dll”)]
静态外部布尔GetConsoleScreenBufferInfo(
IntPtr hConsoleOutput,
输出控制台屏幕缓冲区信息控制台屏幕缓冲区信息
);
[StructLayout(LayoutKind.Sequential)]
结构坐标
{
公共短X;
公众短消息;
}
[StructLayout(LayoutKind.Sequential)]
结构控制台\屏幕\缓冲区\信息
{
公共合作规模;
公共合作地位;
公众短礼;
公共小窗口;
公共合作DWMaximumWindowsSize;
}
[StructLayout(LayoutKind.Sequential)]
结构小矩形
{
公共短左;
公共短上衣;
公短权;
公众短底;
}
const int STD_OUTPUT_HANDLE=-11;
const Int64无效的\u句柄\u值=-1;
公共测试1()
{
初始化组件();
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
bool start=false;
var p=新流程();
p、 StartInfo.FileName=“C:\\Windows\\System32\\cmd.exe”;
开始=p.开始();
institd=p.Id;
}
专用静态字符串ReadALineOfConsoleOutput(IntPtr标准输出,参考短电流位置)
{
if(stdout.ToInt32()==无效的\u句柄\u值)
抛出新的Win32Exception();
//获取控制台信息
如果(!GetConsoleScreenBufferInfo(标准输出,输出控制台\屏幕\缓冲区\信息输出))
抛出新的Win32Exception();
//获取控制台输出行大小
短线尺寸=outInfo.dwSize.X;
//计算要读取的行数
uint numberofLinesToRead=(uint)(outInfo.dwCursorPosition.Y-当前位置);
if(numberofLinesToRead<1)返回null;
//要读取的字符总数
uint nLength=(uint)线宽*linestoread的编号;
StringBuilder lpCharacter=新的StringBuilder((int)nLength);
//从第一行(0,0)的第一个字符读取。
库德·德雷德库德;
dwReadCoord.X=0;
dwReadCoord.Y=当前位置;
如果(!ReadConsoleOutputCharacter(标准输出、lpCharacter、nLength、dwReadCoord、out uint lpNumberOfCharsRead))
抛出新的Win32Exception();
currentPosition=outInfo.dwCursorPosition.Y;
返回lpCharacter.ToString();
}
公共静态异步任务Main()
{
var processId=instit;//CS0120
如果(!FreeConsole())返回;
if(!AttachConsole(processId))返回;
IntPtr stdout=GetStdHandle(标准输出句柄);
短路电流位置=0;
while(true)
{
var r1=ReadALineOfConsoleOutput(标准输出,参考当前位置);
如果(r1!=null)
txtConsole.Text=r1;//CS0120
}
}
}
}

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

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

 var processId = instId; //CS0120

 txtConsole.Text = r1; //CS0120

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

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

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

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

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

另见