如何以表明一个方法是不成功的 [英] How to indicate that a method was unsuccessful

查看:107
本文介绍了如何以表明一个方法是不成功的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类似的方法,例如说。 CalculatePoint(...)和CalculateListOfPoints(...)。偶尔,他们可能不会成功,并需要指明本给调用者。对于CalculateListOfPoints,它返回一个泛型列表,我可以返回一个空列表,并要求调用者来检查这一点;但点是一个值类型,所以我不能返回空值有

I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there.

我非常希望的方法来'看'类似。一种解决方案可能是将其定义为

Ideally I would like the methods to 'look' similar; one solution could be to define them as

public Point CalculatePoint(... out Boolean boSuccess);
public List<Point> CalculateListOfPoints(... out Boolean boSuccess);

或可选择地返回一个点?对于CalculatePoint,并返回null来表示失败。这将意味着不得不投回到非可空类型,虽然,这似乎是过分了。

or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive.

另一条路线是返回布尔boSuccess,有结果(点或列表)作为一个出参数,并呼吁他们TryToCalculatePoint或东西...

Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something...

什么是最好的做法?

编辑:我不想使用流量控制例外!失败是预料有时

I do not want to use Exceptions for flow control! Failure is sometimes expected.

推荐答案

就个人而言,我想我会用同样的想法的TryParse():使用out参数输出的实际价值,并返回一个布尔值,指示调用是否成功与否

Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not

公共BOOL CalculatePoint(...出点结果) ;

我不使用异常的正常行为(如果你希望的功能,不是为某些条目工作)的粉丝。

I am not a fan of using exception for "normal" behaviors (if you expect the function not to work for some entries).

这篇关于如何以表明一个方法是不成功的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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