The (already linked) new pattern matching feature allows this.
Ordinarily, you'd switch on a value:
switch (this.value) {
case int intValue:
this.value = Math.Max(Math.Min(intValue, Maximum), Minimum);
break;
case decimal decimalValue:
this.value = Math.Max(Math.Min(decimalValue, Maximum), Minimum);
break;
}
But you can use it to switch on a type, if all you have is a type:
switch (type) {
case Type intType when intType == typeof(int):
case Type decimalType when decimalType == typeof(decimal):
this.value = Math.Max(Math.Min(this.value, Maximum), Minimum);
break;
}
Note that this is not what the feature is intended for, it becomes less readable than a traditional if
...else if
...else if
...else
chain, and the traditional chain is what it compiles to anyway. I do not recommend using pattern matching like this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…