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

后端 未结 30 2521
梦毁少年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:20

    You're looking for Discriminated Unions which are a language feature of F#, but you can achieve a similar effect by using a library I made, called OneOf

    https://github.com/mcintyre321/OneOf

    The major advantage over switch (and if and exceptions as control flow) is that it is compile-time safe - there is no default handler or fall through

    void Foo(OneOf o)
    {
        o.Switch(
            a => a.Hop(),
            b => b.Skip()
        );
    }
    

    If you add a third item to o, you'll get a compiler error as you have to add a handler Func inside the switch call.

    You can also do a .Match which returns a value, rather than executes a statement:

    double Area(OneOf o)
    {
        return o.Match(
            square => square.Length * square.Length,
            circle => Math.PI * circle.Radius * circle.Radius
        );
    }
    

提交回复
热议问题