C# 开关类型

标签 c# reflection switch-statement

编辑:This is now available in C# 7.0.


我有以下代码检查给定的 PropertyInfotype

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 语句作用于 PropertyInfovalue 而不是它的 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/

相关文章:

c# - 在 .NET 中更改代码中的 UserAgent

java - 如何判断一个Class是否继承于另一个Class?

java - 重构详细的 switch case 语句

c++ - 错误 : switch quantity not an integer

java - 在字符串中使用 switch

c# - ActionLink 在 URL 中包含当前 {id}

c# - 从 Linq 中的另一个列表项创建列表

C# HashSet2 的工作方式与标准 C# HashSet 完全相同,无需编译

c# - 在不生成程序集的情况下调用 WCF 服务

java - 使用反射访问DialogFragment中的一些字段