具有“出”的类似于TryXX的方法。参数和返回一个可空值类型? [英] TryXXX-like methods with "out" parameters vs returning a nullable value type?

查看:157
本文介绍了具有“出”的类似于TryXX的方法。参数和返回一个可空值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到在C#这样的方法:(这样做,可能会或可能不会给结果的计算)

 布尔TrySomething(SOMETYPE inputData,出SomeOtherType结果){...} 

人们为什么不改用像这样

 可空< SomeOtherType> TrySomething(SOMETYPE inputData){...} 



难道只是性能上的差异?
这是一个结构,所以必须有没有堆分配,对不对?
或我错过了什么?


解决方案

可空是引进 - 仿制药一样 - 在C#2.0。有很多的,早的代码。



和说实话,我不是只返回一个大风扇可空每当东西可以去错了。



你平时有什么是像

SomeOtherType东西(SOMETYPE inputData){...}

这将引发一个例外,如果出现错误。现在,在某些情况下,你想避免异常,所以还存在另一种方式:你给了一个

 布尔TrySomething (SOMETYPE inputData,出SomeOtherType结果){...} 

然而,一个例外是精确什么出了问题,一个布尔值不是。所以,如果它给你,你有更多一点的信息它没有工作。在某些情况下,这可能是足够的。我,我喜欢从一个我目前运行内存和不能做什么了的错误,或任何其他区别了我的收藏没有包含该值的错误。



现在推出了可空的返回值,它是 - 我称之为 - 德鲁伊的知识,知道了并不意味着该值为空,而是出现了错误。这是你需要记录和解释,而 TryXXX 方法的布尔的结果是不言自明的。



在总之,你一无所获,但通过使用可空作为返回值。

I often see methods like this in C#: (doing a computation that may or may not give a result)

bool TrySomething(SomeType inputData, out SomeOtherType result) { ... }

Why people don't use instead something like this?

Nullable<SomeOtherType> TrySomething(SomeType inputData) { ... }

Is it just performance difference? This is a struct, so there must be no heap allocation, right? Or I have missed something?

解决方案

Nullable was introduced - like generics - in C# 2.0. There is a lot of code that predates that.

And to be honest, I am not a big fan of just returning a Nullable whenever something can go wrong.

What you usually have is a method like

SomeOtherType Something(SomeType inputData) { ... }

which will throw an exception if something goes wrong. Now in some cases, you want to avoid an exception, so there is an alternative way: the one you gave.

bool TrySomething(SomeType inputData, out SomeOtherType result) { ... }

However, an exception is precise in what went wrong, a boolean value isn't. So if it gives you false, you have little more information that "It didn't work". In some cases, that might be enough. Me, I like to distinguish a "My collection did not contain that value" error from a "I am currently running out of memory and cannot do anything anymore" error, or whatever else.

Now introducing the Nullable as return value, it is - as I call it - druid knowledge to know that receiving null doesn't mean "The value is null", but "Some error occurred". That is something you would need to document and explain, while the bool result of a TryXXX method is self-explanatory.

In short, you gain nothing but produce slightly more confusing code by using Nullable as a return value.

这篇关于具有“出”的类似于TryXX的方法。参数和返回一个可空值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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