Switching on type with a generic return type

后端 未结 2 639
情深已故
情深已故 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:48

    If I understand your intention correctly - you can do it like this:

    // no need to pass instance of T - why?
    public Mock> Mocked() where T : class
    {
        if (typeof(T) == typeof(Workflow)) {
            // first cast to object, then to return type to avoid compile error
            // compiler does not know mockedWorkFlows is Mock>, but you
            // know it already, because you checked type 'T'
            return (Mock>) (object) mockedWorkFlows; //cannot Workflow to T
        }
        // etc
        return null;
    }
    

    Whether it is good idea or not is a different story.

提交回复
热议问题