publicstaticintSumPositiveNumbers(IEnumerable<object> sequence) { int sum = 0; foreach (var i in sequence) { switch (i) { case0: break; case IEnumerable<int> childSequence: { foreach(var item in childSequence) sum += (item > 0) ? item : 0; break; } caseint n when n > 0: sum += n; break; casenull: thrownew NullReferenceException("Null found in sequence"); default: thrownew InvalidOperationException("Unrecognized type"); } } return sum; }
case 0: 是常见的常量模式。
case IEnumerable childSequence: 是一种类型模式。
case int n when n > 0: 是具有附加 when 条件的类型模式。
case null: 是 null 模式。
default: 是常见的默认事例。
Ref 局部变量和返回结果
此功能允许使用并返回对变量的引用的算法,这些变量在其他位置定义。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicstaticrefintFind(int[,] matrix, Func<int, bool> predicate) { for (int i = 0; i < matrix.GetLength(0); i++) for (int j = 0; j < matrix.GetLength(1); j++) if (predicate(matrix[i, j])) returnref matrix[i, j]; thrownew InvalidOperationException("Not found"); }
public Task<string> PerformLongRunningWork(string address, int index, string name) { if (string.IsNullOrWhiteSpace(address)) thrownew ArgumentException(message: "An address is required", paramName: nameof(address)); if (index < 0) thrownew ArgumentOutOfRangeException(paramName: nameof(index), message: "The index must be non-negative"); if (string.IsNullOrWhiteSpace(name)) thrownew ArgumentException(message: "You must supply a name", paramName: nameof(name));
return longRunningWorkImplementation();
async Task<string> longRunningWorkImplementation() { var interimResult = await FirstWork(address); var secondResult = await SecondStep(index, name); return$"The results are {interimResult} and {secondResult}. Enjoy."; } }
更多的 expression-bodied 成员
C# 7.0 扩展了可作为表达式实现的允许的成员。 在 C# 7.0 中,你可以在属性和索引器上实现构造函数、终结器以及 get 和 set 访问器。 以下代码演示了每种情况的示例: