[英]How can I have conditional out parameters
The method DoSomething()
does Create an Instance of MyClass
but not everyone wants to know the MyClass-Object
sometimes it also fits if you simply know if the action was successful. 方法
DoSomething()
确实创建了MyClass
的实例,但并不是每个人都想知道MyClass-Object
,如果你只是知道动作是否成功,它也适合。
public bool DoSomething(out Myclass myclass = null)
{
// Do something
}
A ref or out parameter cannot have a default value
ref或out参数不能具有默认值
Sure I could simply remove the out-Keyword
but then I needed to assign any variable first, which is not my intention. 当然我可以简单地删除
out-Keyword
然后我需要先分配任何变量,这不是我的意图。
public Myclass DoSomething() //returns null if not successful
{
// Do something
}
Does anyone know a nice Workaround for that? 有谁知道一个很好的解决方法吗?
Just by overloading: 只是通过重载:
public bool DoSomething()
{
myClass i;
return DoSomething(out i);
}
public bool DoSomething(out myClass myclass)
{
myclass = whatever;
return true;
}
And then call DoSomething()
然后调用
DoSomething()
You could wrap the parameter in a class. 您可以将参数包装在类中。
class Arguments
{
public Argument () { Arg = null; }
public Myclass Arg { get; set; }
}
and then use it like: 然后使用它像:
Arguments args;
if (DoSomething (args))
{
// args.Arg is something
}
and define the function like: 并定义如下函数:
bool DoSomething (Arguments args)
{
bool success = false;
if (someaction)
{
args.Arg = new Myclass;
success = true;
}
return success;
}
Alternative, and this is making me feel a bit dirty, use exceptions:- 替代方案,这让我觉得有点脏,使用例外: -
Myclass DoSomething ()
{
if (someactionhasfailed)
{
throw new Exception ("Help");
}
return new Myclass;
}
If you do not want to overload the method, you can always create a new class like: 如果您不想重载该方法,则可以始终创建一个新类,如:
public class Response
{
public bool Success{get;set;}
public Myclass MyclassInstance {get;set;}
}
And the use it as a return parameter of your DoSomething() method with the following signature: 并使用它作为DoSomething()方法的返回参数,具有以下签名:
public Response DoSomething()
{
// Do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.