我正在尝试将c#中"out"关键字的使用形式化为我正在使用的项目,特别是对于任何公共方法.我似乎无法找到任何最佳实践,并想知道什么是好的或坏的.
有时我看到一些方法签名看起来像这样:
public decimal CalcSomething(Date start, Date end, out int someOtherNumber){}
Run Code Online (Sandbox Code Playgroud)
在这一点上,这只是一种感觉,这并不适合我.出于某种原因,我更愿意看到:
public Result CalcSomething(Date start, Date end){}
Run Code Online (Sandbox Code Playgroud)
其中结果是包含小数和someOtherNumber的类型.我认为这使得阅读更容易.它允许扩展Result或添加属性而不会破坏代码.这也意味着此方法的调用者不必在调用之前声明本地作用域"someOtherNumber".根据使用期望,并非所有呼叫者都会对"someOtherNumber"感兴趣.
相比之下,我现在可以在.Net框架中考虑"out"参数有意义的唯一实例是TryParse()等方法.这些实际上使调用者编写更简单的代码,因此调用者主要对out参数感兴趣.
int i;
if(int.TryParse("1", i)){
DoSomething(i);
}
Run Code Online (Sandbox Code Playgroud)
我认为只有在返回类型为bool时才会使用"out",并且预期的用法是调用者总是对"out"参数感兴趣的设计.
思考?
我写了一些关于ref -out声明的代码块.我认为ref最有用.好.为什么我需要用完.我每次都可以使用ref:
namespace out_ref
{
class Program
{
static void Main(string[] args)
{
sinifA sinif = new sinifA();
int test = 100;
sinif.MethodA(out test);
Console.WriteLine(test.ToString());
sinif.MethodB(ref test);
Console.WriteLine(test.ToString());
Console.ReadKey();
}
}
class sinifA
{
public void MethodA(out int a)
{
a = 200;
}
int _b;
public void MethodB(ref int b)
{
_b = b;
b = 2*b;
}
}
}
Run Code Online (Sandbox Code Playgroud)