嵌套泛型的扩展方法

时间:2015-01-23 17:16:04

标签: c# generics extension-methods

我在一个多语言网站上工作,我为我的"本地化"建立了这个结构。实体。

接口:

public interface ILocalizable<T>
    where T : ILocalized
{
    ICollection<T> Content { get; set; }
}

public interface ILocalized
{
    int LanguageId { get; set; }
    virtual Language Language { get; set; }
}

并实施:

public class Entity : ILocalizable<EntityLocalized>
{
    public int Id { get; set; }
    public ICollection<EntityLocalized> Content { get; set; }
}

public class EntityLocalized : ILocalized
{
    public int LanguageId { get; set; }
    public virtual Language Language { get; set; }

    public int EntityId { get; set; }
    public string Title { get; set; }
}

这样做的原因是我可以编写一个扩展方法,允许我以这种方式获取正确的字符串:

Entity entity; // get entity from database
string localizedString = entity.Content.Translate(localized => localized.Title);

一切正常。我只是想创建另一个扩展方法,在构建查询时可以节省一些工作。所以我不必一直写作:

IQueryable<Entity> query; // some query
return query.Include(entity => entity.Content.Select(localized => localized.Language));

所以我有这个:

public static IQueryable<TEntity> WithLocalization<TEntity>(this IQueryable<TEntity> query)
{
    return query.Include(entity => entity.Content.Select(content => content.Language));
}

但显然我需要指定泛型类型。这不会编译。我尝试了一切。

public static IQueryable<TEntity> WithLocalization<TEntity>(this IQueryable<ILocalizable<ILocalized>> set) where TEntity : ILocalizable<ILocalized> {}

IQueryable<Entity> query; // get query
query.WithLocalization(); // intellisense doesn't display and this won't compile

我有点理解原因。它已在那里多次讨论过。我只是想知道如何构建这样的扩展方法,而无需显式使用和传递2种泛型类型,例如:

public static IQueryable<TEntity> WithLocalization<TEntity, TEntityLocalized>(this IQueryable<TEntity> set)           
    where TEntityLocalized : ILocalized
    where TEntity : ILocalizable<TEntityLocalized> {}

谢谢!

2 个答案:

答案 0 :(得分:0)

我想你想......

public static IQueryable<ILocalizable<TEntityLocalized>> WithLocalization<TEntityLocalized>(this IQueryable<ILocalizable<TEntityLocalized>> query)
    where TEntityLocalized : ILocalized {
    return query.Include(entity => entity.Content.Select(content => content.Language));
}

答案 1 :(得分:0)

您无法正确地将TEntity通用参数传播到签名中。

public static IQueryable<ILocalizable<TEntity>> WithLocalization<TEntity>(this IQueryable<ILocalizable<TEntity>> query)
    where TEntity : ILocalized
  {
      return query.Include (entity => entity.Content.Select (content => content.Language));
  }

public class Test
{
   public Test()
   {
      IQueryable<Entity> query;
      query.WithLocalization ();
   }
}

正确编译并提供正确的智能感知。