出"使用&QUOT的最佳实践;在C#中的关键字关键字、QUOT

2023-09-03 00:22:33 作者:偷心大盗°

我想正式的出关键字在C#中使用的一个项目,我在,特别是对于任何公共方法。我似乎无法找到任何最佳做法,在那里,想知道什么是好还是坏。

I'm trying to formalise the usage of the "out" keyword in c# for a project I'm on, particularly with respect to any public methods. I can't seem to find any best practices out there and would like to know what is good or bad.

有时候,我看到了如下一些方法签名:

Sometimes I'm seeing some methods signatures that look like this:

public decimal CalcSomething(Date start, Date end, out int someOtherNumber){}

在这一点上,它只是一种感觉,这不跟我坐好。出于某种原因,我想preFER看到:

At this point, it's just a feeling, this doesn't sit well with me. For some reason, I'd prefer to see:

public Result CalcSomething(Date start, Date end){}

,其中结果是包含一个小数和someOtherNumber一个类型。我想,这使得它更易于阅读。它可以让结果来进行扩展或增加了性能不破code。这也意味着,该方法的调用者不具有调用之前声明一个局部范围someOtherNumber。从使用情况的预期,并非所有的来电都将是感兴趣的是someOtherNumber。

where the result is a type that contains a decimal and the someOtherNumber. I think this makes it easier to read. It allows Result to be extended or have properties added without breaking code. It also means that the caller of this method doesn't have to declare a locally scoped "someOtherNumber" before calling. From usage expectations, not all callers are going to be interested in "someOtherNumber".

作为对比,我能想到的,现在.net框架,其中走出去的参数意义内的唯一实例是像的TryParse()的方法。这实际上使呼叫者写简单的code,即主叫主要将是感兴趣的输出参数。

As a contrast, the only instances that I can think of right now within the .Net framework where "out" parameters make sense are in methods like TryParse(). These actually make the caller write simpler code, whereby the caller is primarily going to be interested in the out parameter.

int i;
if(int.TryParse("1", i)){
  DoSomething(i);
}

我在想,走出去应该只有当返回类型是布尔和预期的用法是这里的出参数将永远是感兴趣的来电,设计使用。

I'm thinking that "out" should only be used if the return type is bool and the expected usages are where the "out" parameters will always be of interest to the caller, by design.

思考?

推荐答案

还有一个原因是,静态code分析(=的FxCop)的一个规则点,你当你使用参数。我会说:只能使用退出当真正需要的互操作类型的场景。在其他情况下,根本就没有退出使用。但也许这只是我?

There is a reason that one of the static code analysis (=FxCop) rules points at you when you use out parameters. I'd say: only use out when really needed in interop type scenarios. In all other cases, simply do not use out. But perhaps that's just me?