public static int DiceSum4(IEnumerable<object> values) {
var sum = 0;
foreach (var item in values) {
switch (item) {
case 0:
break;
case int val:
sum += val;
break;
case IEnumerable<object> subList when subList.Any():
sum += DiceSum4(subList);
break;
case IEnumerable<object> subList:
break;
case null:
break;
default:
throw new InvalidOperationException("unknown item type");
}
}
return sum;
}
本地函数
使用场景:当某一函数 A 需要通过另一个函数 B 来进行更加复杂的处理,但其他地方都不会用到 B,此时,我们可以将 B 声明在 A 的内部,示例如下:
public static IEnumerable<char> AlphabetSubset3(char start, char end) {
if (start < 'a' || start > 'z')
throw new ArgumentOutOfRangeException(paramName: nameof(start), message: "start must be a letter");
if (end < 'a' || end > 'z')
throw new ArgumentOutOfRangeException(paramName: nameof(end), message: "end must be a letter");
if (end <= start)
throw new ArgumentException($"{nameof(end)} must be greater than {nameof(start)}");
return alphabetSubsetImplementation();
IEnumerable<char> alphabetSubsetImplementation() {
for (var c = start; c < end; c++)
yield return c;
}
}
public const int One = 0b0001;
public const int Two = 0b0010;
public const int Four = 0b0100;
public const int Eight = 0b1000;
如果二进制很长,可通过 _ 作为数字分隔符通常更易于查看,如下:
public const int Sixteen = 0b0001_0000;
public const int ThirtyTwo = 0b0010_0000;
public const int SixtyFour = 0b0100_0000;
public const int OneHundredTwentyEight = 0b1000_0000;
数字分隔符可以出现在常量的任何位置:
// 对于十进制数字,通常将其用作千位分隔符
public const long BillionsAndBillions = 100_000_000_000;
// 数字分隔符也可以与 decimal、float 和 double 类型一起使用
public const double AvogadroConstant = 6.022_140_857_747_474e23;
public const decimal GoldenRatio = 1.618_033_988_749_894_848_204_586_834_365_638_117_720_309_179M;