Is there a better alternative than this to 'switch on type'?

后端 未结 30 2863
梦毁少年i
梦毁少年i 2020-11-22 03:28

Seeing as C# can\'t switch on a Type (which I gather wasn\'t added as a special case because is relationships mean that more than one distinct

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 03:56

    As per C# 7.0 specification, you can declare a local variable scoped in a case of a switch:

    object a = "Hello world";
    switch (a)
    {
        case string myString:
            // The variable 'a' is a string!
            break;
        case int myInt:
            // The variable 'a' is an int!
            break;
        case Foo myFoo:
            // The variable 'a' is of type Foo!
            break;
    }
    

    This is the best way to do such a thing because it involves just casting and push-on-the-stack operations, which are the fastest operations an interpreter can run just after bitwise operations and boolean conditions.

    Comparing this to a Dictionary, here's much less memory usage: holding a dictionary requires more space in the RAM and some computation more by the CPU for creating two arrays (one for keys and the other for values) and gathering hash codes for the keys to put values to their respective keys.

    So, for as far I know, I don't believe that a faster way could exist unless you want to use just an if-then-else block with the is operator as follows:

    object a = "Hello world";
    if (a is string)
    {
        // The variable 'a' is a string!
    } else if (a is int)
    {
        // The variable 'a' is an int!
    } // etc.
    

提交回复
热议问题