Switching on type with a generic return type

后端 未结 2 642
情深已故
情深已故 2021-01-14 18:13

I\'m working on making EF easier to unit test by writing some helpers that will make properties for me. I have a couple of backing fields

private Mock

        
2条回答
  •  生来不讨喜
    2021-01-14 18:38

    It is possible to seriously abuse C#7's switch to achieve what you want by switching on an unrelated value and using the var pattern with when guards:

    public Mock> Mocked() where T : class
    {
        switch(true)
        {
            case var _ when typeof(T) == typeof(Workflow):
                return ...
            case var _ when typeof(T) == typeof(WorkflowError):
                return ...
            default:
                return null;
        }
    }
    

    Being able to match on types in switch statements is a very common request. There are proposals for improvements to C# on the official language repo on github (see Proposal: switch on System.Type and pProposal: Pattern match via generic constraint). As and when more pattern matching functionality is added to C# (currently, set for "a 7.X release"), we may get nicer syntax for this functionality.

提交回复
热议问题