2017-03-08 93 views
3

我使用Visual Studio代码和VS 2017发布后我刚刚安装了Net Core Tools 1.1.1,希望实现新的C#7模式匹配功能,如来自MSFT的this示例中的一个:模式切换语句

switch(shape) 
{ 
    case Circle c: 
     WriteLine($"circle with radius {c.Radius}"); 
     break; 
    case Rectangle s when (s.Length == s.Height): 
     WriteLine($"{s.Length} x {s.Height} square"); 
     break; 
    case Rectangle r: 
     WriteLine($"{r.Length} x {r.Height} rectangle"); 
     break; 
    default: 
     WriteLine("<unknown shape>"); 
     break; 
    case null: 
     throw new ArgumentNullException(nameof(shape)); 
} 

我要实现与模式switch语句来代替if-then-else长序列:

var property = obj.GetType().GetProperty("XYZ"); 
var propertyType = Type.GetType(property.PropertyType.FullName); 

switch (propertyType) 
{ 
    case Boolean b: 
     writeLine("Convert a string to a Boolean"); 
     break; 

    case Int32 i: 
     WriteLine("Convert a string to a Int32"); 
     break; 

    default: 
     WriteLine("unknown type, skip"); 
     break; 
}  

当我尝试编译我收到以下错误:

'Type类型的表达式不能由类型为bool的模式处理。 [efcore]'

'Type类型的表达式不能由类型为int的模式处理。 [efcore]'

我在做什么错?

回答

6

您需要在切换,而不是在价值类型:

var property = obj.GetType().GetProperty("XYZ"); 
var value = property.GetValue(obj); 

switch (value) 
{ 
    case Boolean b: 
     ... 
    ... 
}