【发布时间】:2018-01-19 14:09:46
【问题描述】:
我喜欢在nullable int 上使用pattern-matching,即int?:
int t = 42;
object tobj = t;
if (tobj is int? i)
{
System.Console.WriteLine($"It is a nullable int of value {i}");
}
但是,这会导致以下语法错误:
- CS1003: Syntax error, ';',
- CS1525: Invalid expression term ')',
- CS0103: The name 'i' does not exist in the current context。
'i)' 用红色波浪线标记。
表达式在使用旧运算符 is 时编译:
int t = 42;
object tobj = t;
if (tobj is int?)
{
System.Console.WriteLine($"It is a nullable int");
}
string t = "fourty two";
object tobj = t;
if (tobj is string s)
{
System.Console.WriteLine($@"It is a string of value ""{s}"".");
}
也可以按预期工作。
(我正在使用c#-7.2 并使用.net-4.7.1 和.net-4.6.1 进行了测试)
我认为它与运算符优先级有关。因此,我尝试在几个地方使用括号,但这没有帮助。
为什么会出现这些语法错误,我该如何避免?
【问题讨论】:
-
您为什么要尝试使用可为空的类型?您是否尝试使用模式匹配创建可选值,例如 F# 的可区分联合?他们来了,只是不在 C# 8 时间范围内(我认为)。如果您使用公共接口为有效值和缺失值创建两种不同的类型,例如
interface IOption<T>{}; class MyValidClass:IOption<T>{...} class MyEmptyType:IOption<T>{},则可以模拟它们。接口和选项甚至不需要有任何方法 -
@PanagiotisKanavos 可空类型来自代码的不同部分,使用可空类型的选择与我在这里尝试的模式匹配无关。
标签: c#-7.2 .net-4.7.1 .net-4.6.1 c# pattern-matching nullable c#-7.0