从方法返回值 [英] returning values from a method

查看:109
本文介绍了从方法返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自组装恐龙和OO新手:我有一个方法可以调用一个外部程序,该程序要么在标准输出中返回零返回码一些数据,要么在标准错误中返回非零返回码和错误消息,也许在标准输出中返回错误消息.这就是我所做的:

from an assembler dinosaur and OO newbie : I have a method that calls an external program which either returns a zero return code some data in stdout, or returns with a non-zero return code and error messages in stderr and maybe stdout. This is what I''ve done :

class methodReturn
{
    public int rc { get; set; }
    public string message { get; set; }
    public string returnData { get; set; }
}
.
.
methodReturn r = GetStuff(someParm);
if (r.rc != 0)
{
  MessageBox.Show(r.message);
  Application.Exit();
}
.
.
private methodReturn GetStuff(string myParm)
{
    methodReturn r = new methodReturn();
    ProcessStartInfo pInfo = new ProcessStartInfo();
    .
    .
    pInfo.UseShellExecute = false;
    pInfo.RedirectStandardOutput = true;
    pInfo.RedirectStandardError = true;
    Process p = Process.Start(pInfo);
    p.WaitForExit();
    string ProcessStandardOutput = p.StandardOutput.ReadToEnd();
    string ProcessStandardError = p.StandardError.ReadToEnd();
    int rc = p.ExitCode;
    p.Close();
    if (rc == 0)
    {
        r.returnData = ProcessStandardOutput;
        r.message = null;
    }
    else
    {
        r.rc = 8;
        r.message = "Error : \n" +
                    "Exit Code : " + rc + "\n" +
                    "StandardOutput : \n" + ProcessStandardOutput + "\n" +
                    "StandardError  : \n" + ProcessStandardError;
        r.returnData  = null;
    }
    return r;
}



我猜测创建一个仅用于调用方法的类不是一个好的OO实践.有什么更好的方法?谢谢.

[修改:将lang从msil更改为cs]



I''m guessing creating a class just to call a method is not good OO practice. What would be a better way? thanks.

[Modified: changed lang from msil to cs]

推荐答案

was8309写道:
was8309 wrote:

我猜想创建一个类只是为了调用一个方法不是一个好的OO实践

I''m guessing creating a class just to call a method is not good OO practice



这是完全可以接受的海事组织.框架中的许多事件具有EventArgs纯粹是针对一个事件和相应委托的派生类-几乎相同.

无论何时需要从方法返回多个值,我都会根据需要创建一个类/结构,这比使用refs/outs更为整洁,这是唯一的其他方法.



That''s quite acceptable IMO. Many events in the framework have EventArgs derived class purely for the one event and corresponding delegates - this is much the same.

Wherever I need to return multiple values from a method I create a class/struct as appropriate, much tidier than using refs/outs which is the only other way.


这篇关于从方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆