c#7.0:开启System.Type [英] c# 7.0: switch on System.Type
问题描述
没有现有的问题可以回答这个问题。
No existing question has an answer to this question.
在c#7中,我可以直接在 System.Type
上切换吗? ?
In c# 7, can I switch directly on a System.Type
?
当我尝试:
switch (Type)
{
case typeof(int):
break;
}
它告诉我 typeof(int)
必须是一个常量表达式。
it tells me that typeof(int)
needs to be a constant expression.
是否有一些语法糖可以让我避免直接使用 case nameof(int):
比较平等的类型? case语句中的 nameof(T)
并不完全好,因为名称空间。因此,尽管名称冲突可能不适用于 int
,但它将适用于其他比较。
Is there some syntatic sugar that allows me to avoid case nameof(int):
and directly compare the types for equality? nameof(T)
in a case statement is not completely good because namespaces. So although name collision is probably not be applicable for int
, it will be applicable for other comparisons.
换句话说,我m尝试比此类型更安全:
In other words, I'm trying to be more type-safe than this:
switch (Type.Name)
{
case nameof(Int32):
case nameof(Decimal):
this.value = Math.Max(Math.Min(0, Maximum), Minimum); // enforce minimum
break;
}
推荐答案
(已链接)新模式匹配功能允许这样做。
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;
}
请注意,这不是该功能的目的,因此可读性降低比传统的 if
... else if
... else if
... else
链,无论如何,传统链都是编译后的。我不建议使用这种模式匹配。
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.
这篇关于c#7.0:开启System.Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!