小编典典

如何在Type上使用开关盒?[重复]

c#

这个问题已经在这里有了答案

7年前关闭。

可能重复:
是否有比“打开类型”更好的替代方法?

我需要遍历类的所有属性,并检查它的int类型是否需要执行某些操作,如果它的字符串是..然后执行某些操作。我需要使用开关盒。在这里,我以以下方式使用switch,但是它要求一些常数。参见下面的代码:

 public static bool ValidateProperties(object o)
{
    if(o !=null)
    {
        var sourceType = o.GetType();
        var properties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Static);
        foreach (var property in properties)
        {
            var type = property.GetType();
            switch (type)
            {
                *case typeof(int):* getting error here
                    // d
            }
        }
    }
}

我也想知道,我应该使用哪种检查,typeof(int)或typeof(Int32)?


阅读 369

收藏
2020-05-19

共1个答案

小编典典

您不能使用switch块来测试type的值Type。编译代码会给您一个错误,例如:

开关表达式或大小写标签必须是bool,char,string,integral,enum或相应的可为空的类型

您将需要使用if- else语句。

另外:typeof(int)typeof(Int32)是等效的。int是关键字,Int32是类型名称。

更新

如果您期望大多数类型都是固有类型,则可以通过将开关块与一起使用来提高性能Type.GetTypeCode(...)

例如:

switch (Type.GetTypeCode(type))
{
    case TypeCode.Int32:
        // It's an int
        break;

    case TypeCode.String:
        // It's a string
        break;

    // Other type code cases here...

    default:
        // Fallback to using if-else statements...
        if (type == typeof(MyCoolType))
        {
            // ...
        }
        else if (type == typeof(MyOtherType))
        {
            // ...
        } // etc...
}
2020-05-19