使用通用返回类型打开类型 [英] Switching on type with a generic return type
问题描述
我正在通过编写一些可以为我提供属性的助手来使EF易于进行单元测试.我有两个支持领域
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.
但是,即使我添加了Workflow
的类约束,我也会遇到相同的错误.
However, even if I add a class constraint of Workflow
, I get the same error.
我也尝试打开t's
类型,但是那里也没有运气.除对象外,其他几个后备字段的类型不共享一个共同的祖先.我想做的事有可能吗?
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?
推荐答案
如果我正确理解了您的意图-您可以这样做:
If I understand your intention correctly - you can do it like this:
// no need to pass instance of T - why?
public Mock<DbSet<T>> Mocked<T>() 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<DbSet<T>>, but you
// know it already, because you checked type 'T'
return (Mock<DbSet<T>>) (object) mockedWorkFlows; //cannot Workflow to T
}
// etc
return null;
}
这是个好主意还是另外一个故事.
Whether it is good idea or not is a different story.
这篇关于使用通用返回类型打开类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!