这是更好的,使用可为空或布尔返回+ out参数 [英] which is better, using a nullable or a boolean return+out parameter
问题描述
可以说我有一个需要返回一些整型值的函数。但它也可能失败,我需要知道什么时候它。
Lets say I have a function that needs to return some integer value. but it can also fail, and I need to know when it does.
哪个是更好的办法?
public int? DoSomethingWonderful()
或
public bool DoSomethingWonderful(out int parameter)
这是可能更多的作风问题,但我还是好奇的人会采取哪一种方案
this is probably more of a style question, but I'm still curious which option people would take.
编辑:。澄清,这段代码会谈到一个黑盒子(可以称之为云没有,一个黑盒子。不,等等。云计算是)。我不关心的为什么的失败。我只需要知道,如果我有一个有效的价值或没有。
clarification, this code talks to a black box (lets call it a cloud. no, a black box. no, wait. cloud. yes). I dont care why it failed. I would just need to know if I have a valid value or not.
推荐答案
我喜欢为空的版本更好,因为你可以使用空COALESCE运营商? ,就可以了,例如:
I like the nullable version better, because you can use the null coalesce operator ?? on it, e.g.:
int reallyTerrible = 0;
var mightBeWonderful = DoSomethingWonderful() ?? reallyTerrible;
这篇关于这是更好的,使用可为空或布尔返回+ out参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!