out 参数与约定
Coddy 面向 Ruby 开发者的 C# 课程的第 25 课,共 48 课。
Ruby 会将多个结果作为一个数组返回:return true, value * 2会构建[true, 8],而ok, n = ...会对其进行解构。Ruby 方法永远无法重新赋值给调用者的局部变量。C# 的out参数正是这样做的,而且编译器要求方法在每条正常执行路径上都为它赋值,包括返回 false 的路径。Ruby 代码通常会在没有结果时返回 nil,而 bool 加 out 的方式可以将实际的 0 和无结果区分开来。
Out 参数通过调用者的绑定返回额外的值,并且必须在每条路径上都赋值。bool 加 out 的约定可以区分缺失的结果和有效的零值。对于全为负数的序列,从零开始设置最大值是不正确的;处理空序列后,应使用第一个值进行初始化。
Ruby 参考
def try_double(value)
return false, 0 if value.negative?
return true, value * 2
end
ok, n = try_double(4)
puts ok ? n : "invalid"
ok, n = try_double(-1)
puts ok ? n : "invalid"C# 辅助声明
static bool TryDouble(int value, out int result) { if (value < 0) { result = 0; return false; } result = value * 2; return true; }Main 中的 C# 语句
int n;
Console.WriteLine(TryDouble(4, out n) ? n.ToString() : "invalid");
Console.WriteLine(TryDouble(-1, out n) ? n.ToString() : "invalid");这些是针对特定内容的教学摘录。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关声明和语句。
Ruby 输出:
8
invalidC# 输出:
8
invalid挑战
简单实现 TryMaximum(int[] values, out int maximum)。如果数组为空,返回 false 并将 maximum 设为零。否则返回 true,并将 maximum 设为最大值,即使所有值都是负数。Solve 会格式化结果。
编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述行,调用 Exercise.Solve,验证输入未被修改,并在结果末尾输出一个换行符。保留声明的 API。不要添加第二个 Main,也不要输出诊断信息。
锁定的启动程序还会单独测试导出的辅助函数或类 API,而不仅仅测试 Solve 包装器。
亲手试试
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Ints(input[0]); string before0=Snapshot(a0);
int maximum; if (Exercise.TryMaximum(new int[0], out maximum) || maximum != 0 || !Exercise.TryMaximum(new[]{-8,-3},out maximum) || maximum != -3) throw new Exception("TryMaximum API");
var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C#中的所有课
自己练习: C# 在线编译器