【问题标题】:How to Transform in to one function using generics or dynamic?如何使用泛型或动态转换为一个函数?
【发布时间】:2014-07-22 09:19:33
【问题描述】:

我有两种非常相似的方法。如何使用泛型(或动态 .NET 特性)将通用功能提取到一个函数中?

private IEnumerable<BlogPost> GetBlogPostToday(IBlogPostRepository repo)
{
    return repo
        .GetAllQueryAble()
        .Where(p => DbFunctions.TruncateTime(p.DateAdded) == DateTime.Today)
        .Select(p => p).AsEnumerable();
}

private IEnumerable<BlogView> GetBlogViewsToday(IBlogViewRepository repo)
{
    return repo
        .GetAllQueryAble()
        .Where(p => DbFunctions.TruncateTime(p.DateAdded) == DateTime.Today)
        .Select(p => p).AsEnumerable();
}

【问题讨论】:

  • 里面的.Select(p =&gt; p).AsEnumerable(); 做的很少,顺便说一句
  • @Groo 好的,谢谢你的信息

标签: c# .net asp.net-mvc linq


【解决方案1】:

你也许可以这样做:

public interface IHazDateAdded {
   DateTime DateAdded {get;}
}
// extend the types (fortunately we can do this in partial classes)
public partial class Foo : IHazDateAdded {}
public partial class Bar : IHazDateAdded {}

private static IQueryable<T> GetToday<T>(this IQueryable<T> source)
    where T : IHazDateAdded
{
    return source.Where(
         p => DbFunctions.TruncateTime(p.DateAdded) == DateTime.Today);
}

这至少可以减少一些重复代码。不过,就个人而言,我建议改用 range 查询:

private static IQueryable<T> GetToday<T>(this IQueryable<T> source)
    where T : IHazDateAdded
{
    DateTime start = DateTime.Today, end = start.AddDays(1);
    return source.Where(p => p.DateAdded >= start && p.DateAdded < end);
}

那么你有:

private IEnumerable<BlogPost> GetBlogPostToday(IBlogPostRepository blogPost)
{
    return blogPost.GetAllQueryAble().GetToday();
}

private IEnumerable<BlogView> GetBlogViewsToday(IBlogViewRepository blogViewRepo)
{
    return blogViewRepo.GetAllQueryAble().GetToday();
}

然后我们可以通过以下方式进一步扩展/减少它:

public interface IRepository<T> {
    IQueryable<T> GetAllQueryable();
}
interface IBlogPostRepository : IRepository<BlogPost> { /* ... */ }
interface IBlogViewRepository : IRepository<BlogView> { /* ... */ }

允许:

private IEnumerable<T> GetToday<T>(IRepository<T> repository)
    where T : IHazDateAdded
{
    return repository.GetAllQueryAble().GetToday();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多