我怎样才能有条件输出参数

Luc*_*key 4 c#

该方法DoSomething()确实创建了一个实例,MyClass但不是每个人都想知道,MyClass-Object如果您只是知道该操作是否成功,它有时也适合.

这不编译

public bool DoSomething(out Myclass myclass = null)
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

ref或out参数不能具有默认值

当然我可以简单地删除out-Keyword但后来我需要先分配任何变量,这不是我的意图.

这可能是一种解决方法,但我希望bool成为返回类型

public Myclass DoSomething() //returns null if not successful
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

有谁知道一个很好的解决方法吗?

Tho*_*oub 7

只是通过重载:

public bool DoSomething()
{
    myClass i;
    return DoSomething(out i);
}

public bool DoSomething(out myClass myclass)
{
    myclass = whatever;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

然后打电话 DoSomething()


Ski*_*izz 4

您可以将参数包装在类中。

class Arguments
{
public Argument () { Arg = null; }
public Myclass Arg { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

Arguments args;
if (DoSomething (args))
{
  // args.Arg is something
}
Run Code Online (Sandbox Code Playgroud)

并定义函数如下:

bool DoSomething (Arguments args)
{
  bool success = false;
  if (someaction)
  {
    args.Arg = new Myclass;
    success = true;
  }
  return success;
}
Run Code Online (Sandbox Code Playgroud)

另一种选择,这让我感觉有点肮脏,使用异常:-

Myclass DoSomething ()
{
  if (someactionhasfailed)
  {
    throw new Exception ("Help");
  }
  return new Myclass;
}
Run Code Online (Sandbox Code Playgroud)