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

后端 未结 30 2515
梦毁少年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 04:01

    Given inheritance facilitates an object to be recognized as more than one type, I think a switch could lead to bad ambiguity. For example:

    Case 1

    {
      string s = "a";
      if (s is string) Print("Foo");
      else if (s is object) Print("Bar");
    }
    

    Case 2

    {
      string s = "a";
      if (s is object) Print("Foo");
      else if (s is string) Print("Bar");
    }
    

    Because s is a string and an object. I think when you write a switch(foo) you expect foo to match one and only one of the case statements. With a switch on types, the order in which you write your case statements could possibly change the result of the whole switch statement. I think that would be wrong.

    You could think of a compiler-check on the types of a "typeswitch" statement, checking that the enumerated types do not inherit from each other. That doesn't exist though.

    foo is T is not the same as foo.GetType() == typeof(T)!!

提交回复
热议问题