我有一个抽象类叫水果。 然后我有一个派生类叫苹果。C#泛型和特定扩展方法组合歧义
我有这两个扩展方法:
public static IQueryable<TFruit> WithEagerLoading<TFruit>(this IQueryable<TFruit> query) where TFruit : Fruit
{
return query.EagerLoad(x => x.Distributors); // Fruit.Distributors
}
public static IQueryable<Apple> WithEagerLoading(this IQueryable<Apple> query)
{
query = query.EagerLoad(x => x.AppleBrands); // Apple.AppleBrands
// now bubble up to base extension method
return query.WithEagerLoading<Apple>();
}
现在,这里是通用的方法,我有一个存储库:
public TFruit FindById<TFruit>(int fruitId) where TFruit : Fruit
{
var query = _ctx.Fruits // IQueryable<Fruit>
.OfType<TFruit>(); // IQueryable<TFruit>
query = query.WithEagerLoading();
return query.SingleOrDefault(x => x.FruitId == fruitId);
}
这个问题我有,当我这样做:
var apple = repository.FindById<Apple>(1);
它进入IQueryable<Fruit>
扩展方法。
我想让它进入IQueryable<Apple>
扩展方法。对于其他类型的水果,它应该进入IQueryable<TFruit>
扩展方法。
我以为编译器会选择最具体的扩展方法。
任何想法?
编辑
感谢您的意见/答案。我现在看到为什么这不起作用。
那么有什么选择来解决这个问题?如果我创建了一个方法:
public static IQueryable<Apple> WithAppleEagerLoading(this IQueryable<Apple> query)
我会怎么称呼它从我的通用仓库?我会检查的TFruit
类型:
public TFruit FindById<TFruit>(int fruitId) where TFruit : Fruit
{
var query = _ctx.Fruits // IQueryable<Fruit>
.OfType<TFruit>(); // IQueryable<TFruit>
if (typeof(TFruit) == typeof(Apple))
query = query.WithAppleEagerLoading();
else
query = query.WithEagerLoading();
return query.SingleOrDefault(x => x.FruitId == fruitId);
}
这是不是很好 - 考虑到我有大约20派生类型。
任何人都可以提供一个替代方案,我试图做什么?
泛型不是模板。 http://blogs.msdn.com/b/ericlippert/archive/2009/07/30/generics-are-not-templates.aspx – Ani 2011-02-02 04:50:29
不确定这是否可能,因为`query.WithEagerLoading()`实际上只是简写对于`MyHelper.WithEagerLoading(query)`,它总是调用第一个泛型方法,而不是特定的方法。 – Vadim 2011-02-02 04:54:56