什么时候“尝试"?应该在C#方法名称中使用? [英] When is "Try" supposed to be used in C# method names?

查看:72
本文介绍了什么时候“尝试"?应该在C#方法名称中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在与我们的同事讨论方法名称以"Try"开头的含义.

We were discussing with our coworkers on what it means if the method name starts with "Try".

有以下意见:

  • 当方法可以返回空值时,请使用尝试".
  • 当方法不会引发异常时,请使用尝试".

正式定义是什么?方法名称中的尝试"是什么意思? 是否有关于此的官方指南?

What is the official definition? What does "Try" say in the method name? Is there some official guideline about this?

推荐答案

这被称为 TryParse 模式,并且已由Microsoft记录. MSDN官方异常和性能页面:

This is known as the TryParse pattern and has been documented by Microsoft. The official Exceptions and Performance MSDN page says:

为在常见情况下可能引发异常的成员考虑TryParse模式,以避免与异常相关的性能问题.

Consider the TryParse pattern for members that may throw exceptions in common scenarios to avoid performance problems related to exceptions.

因此,如果您具有常规用例的代码意味着它可能引发异常(例如解析int),则 TryParse 模式很有意义.

Thus if you have code for which a regular use case would mean that it might throw an exception (such as parsing an int), the TryParse pattern makes sense.

这篇关于什么时候“尝试"?应该在C#方法名称中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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