简体   繁体   English

C#编码约定公共/私有上下文

[英]c# coding convention public/private contexts

I'm learning C# and I'm creating a simple WinForms application, and what it does is starting a simple OpenVPN client: 我正在学习C#,并且正在创建一个简单的WinForms应用程序,它的工作是启动一个简单的OpenVPN客户端:

    void button_Connect_Click(object sender, EventArgs e)
    {
        var proc = new Process();
        proc.StartInfo.FileName = "CMD.exe";
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.WorkingDirectory = @"C:\Program Files (x86)\OpenVPN\bin";
        proc.StartInfo.Arguments = "/c openvpn.exe --config config.ovpn --auto-proxy";

        // set up output redirection
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.RedirectStandardError = true;
        // Input
        proc.StartInfo.RedirectStandardInput = true;

        // Other
        proc.EnableRaisingEvents = true;
        proc.StartInfo.CreateNoWindow = false;
        // see below for output handler
        proc.ErrorDataReceived += proc_DataReceived;
        proc.OutputDataReceived += proc_DataReceived;

        proc.Start();

        StreamWriter myStreamWriter = proc.StandardInput;
        proc.BeginErrorReadLine();
        proc.BeginOutputReadLine();

        proc.WaitForExit();
    }

    void proc_DataReceived(object sender, DataReceivedEventArgs e)
    {
        // output will be in string e.Data
        if (e.Data != null)
        {
            string Data = e.Data.ToString();
            if (Data.Contains("Enter Auth Username"))
            {
                myStreamWriter("myusername");
            }
            //MessageBox.Show(Data);
        }
    }

What it does now, is send all the output of the CMD to my program, which run commands depending on the output. 现在要做的是将CMD的所有输出发送到我的程序,该程序根据输出运行命令。

My current issue is, I need to write to the stream. 我当前的问题是,我需要写流。 I use myStreamWriter in proc_DataReceived , however it's not in the same context so it doesn't work. 我用myStreamWriterproc_DataReceived ,但它不是在同样的情况下,因此不能正常工作。

I get the following error: The name 'myStreamWriter' does not exist in the current context , which is obviously non existent in that scope. 我收到以下错误: The name 'myStreamWriter' does not exist in the current context在该范围内显然不存在。

How do I make this work? 我该如何工作? Get/set properties? 获取/设置属性? Like I said I'm quite new to C# so any help is appreciated. 就像我说的那样,我对C#还是很陌生,因此可以提供任何帮助。

In your form, add this field: 在您的表单中,添加以下字段:

public class Form1Whatevver: Form {
    private StreamWriter myStreamWriter;
}

Then in your code: 然后在您的代码中:

proc.Start();

this.myStreamWriter = proc.StandardInput;

proc.BeginErrorReadLine();
proc.BeginOutputReadLine();

Now, myStreamWriter will be available to proc_DataReceived() 现在, proc_DataReceived()将可用于proc_DataReceived()

void proc_DataReceived(object sender, DataReceivedEventArgs e)
    {
        // output will be in string e.Data
        if (e.Data != null)
        {
            string Data = e.Data.ToString();
            if (Data.Contains("Enter Auth Username"))
            {
                if (myStreamWriter != null) // Just in case
                {
                    myStreamWriter("myusername");
                }
            }
            //MessageBox.Show(Data);
        }
    }

The concept you are talking about is Scope not context. 您正在谈论的概念是范围而不是上下文。


The are several ways you could alter your code so that you can access myStreamWriter from proc_DataReceived . 的几种方法,你可以改变你的代码,以便您可以访问myStreamWriterproc_DataReceived

Arguably the simplest, is to pass the object you wish to effect as a parameter to the function. 可以说,最简单的方法是将希望实现的对象作为参数传递给函数。 This is often a good approach in the perspective of future multi-threading and a drive towards a functional style. 从将来的多线程和追求功能风格的角度来看,这通常是一种好方法。

    void proc_DataReceived(
        object sender, 
        DataReceivedEventArgs e,
        StreamWriter writer)
    {
        ...
        writer("myusername");
        ...
    }

However proc_DataReceived is obviously an event handler and you probably don't want to change the signature of the function. 但是proc_DataReceived显然是一个事件处理程序,您可能不想更改函数的签名。


If you declare myStreamWriter as a Private Member Variable at the class level you will be able to access from anywhere within the class. 如果在类级别将myStreamWriter声明为私有成员变量,则可以从类中的任何位置进行访问。 The this is optional but good form. this是可选的但很好的形式。

class YourForm : Form
{
    private StreamWriter myStreamWriter;

    void button_Connect_Click(...
    {
        ...
        this.myStreamWriter = proc.StandardInput;
        ...
    }

    void proc_DataRecieved(...
    {
        ...
        this.myStreamWriter("myusername");
        ...

    }
}

A property implementation is not necessary unless you want to access the StreamWriter from outside the class/form. 除非您要从类/窗体外部访问StreamWriter ,否则不需要实现属性。

The simple quick-fix is to define myStreamWriter as a field in the class (ie outside the scopes of your methods), then instantiate it from within one of the scopes: 简单的快速修复是将myStreamWriter定义为类中的一个字段(即,在方法范围之外),然后从范围之一中实例化它:

private StreamWriter _myStreamWriter;

void button_Connect_Click(object sender, EventArgs e)
{
    // Do some stuff

    _myStreamWriter = proc.StandardInput;

    // Do some stuff
}

Having done that should let you use it wherever you want within the class. 完成该操作后,您就可以在课堂上任何地方使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM