Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

c# - Switching on type with a generic return type

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<DbSet<Workflow>> mockedWorkFlows;
private Mock<DbSet<WorkflowError>> mockedWorkFlowErrors;

And I want a generic function to be able to return me the correct backing field with the following function

public Mock<DbSet<T>> Mocked<T>(T t) where T : class
{
   if ( (object)t is Workflow)
   {
       return mockedWorkFlows; //cannot Workflow to T
    }
}

There are several private backing fields which I want to be returned based on the type passed it.

However, even if I add a class constraint of Workflow, I get the same error.

I also tried switching on t's type but no luck there either. The types of the several backing fields do not share a common ancestor, other than object. Is what I'm trying to do possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<DbSet<T>> Mocked<T>() 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...