编辑:This is now available in C# 7.0.
我有以下代码检查给定的 PropertyInfo
的 type
。
PropertyInfo prop;
// init prop, etc...
if (typeof(String).IsAssignableFrom(prop.PropertyType)) {
// ...
}
else if (typeof(Int32).IsAssignableFrom(prop.PropertyType)) {
// ...
}
else if (typeof(DateTime).IsAssignableFrom(prop.PropertyType)) {
// ...
}
有没有办法在这种情况下使用 switch
语句?这是我目前的解决方案:
switch (prop.PropertyType.ToString()) {
case "System.String":
// ...
break;
case "System.Int32":
// ...
break;
case "System.DateTime":
// ...
break;
default:
// ...
break;
}
我认为这不是最佳解决方案,因为现在我必须给出给定 type
的完全限定 String
值。有什么建议吗?
最佳答案
现在在 C# 7.0 中可用。
这个解决方案是针对我原来的问题; switch
语句作用于 PropertyInfo
的 value
而不是它的 PropertyType
:
PropertyInfo prop;
// init prop, etc...
var value = prop.GetValue(null);
switch (value)
{
case string s:
// ...
break;
case int i:
// ...
break;
case DateTime d:
// ...
break;
default:
// ...
break;
}
稍微更通用的答案:
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));
}
Reference: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
关于C# 开关类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34345894/