【问题标题】:Is it possible to have a param array of Func's是否有可能有一个 Func 的参数数组
【发布时间】:2012-02-15 10:26:47
【问题描述】:

类似下面的构造可能吗?

  public IQueryable<T> AllWithFetch<TRelated>(IQueryable<T> existing, params Expression<Func<T, TRelated>>[] fetchExpressions)
  {
     return fetchExpressions.Aggregate(existing, (current, exp) => current.Fetch(exp));
  }

然后可以这样调用...

var allDetails = this.preGrantDetailRepository
                .AllWithFetch(this.preGrantDetailRepository.All, x => x.Case, x => x.CaseOwner)

基本上,我试图将 NHibernate 的获取策略添加到我们的抽象存储库中,以使我们能够在不破坏存储库模式的情况下从逻辑层指定这些策略。例如,如果我们从 NHibernate 更改为另一个 ORM,我们可以提供相同的存储库方法,但为该 ORM 实现。

当我尝试在 param 数组中链接多个 func 时出现问题。

所以这行得通...

var allDetails = this.preGrantDetailRepository
                .AllWithFetch(this.preGrantDetailRepository.All, x => x.Case)

但这失败了,“类型参数不能从它们的用法中推断出来”消息

var allDetails = this.preGrantDetailRepository
                .AllWithFetch(this.preGrantDetailRepository.All, x => x.Case, x => x.CaseOwner)

我正在使用 .NET 3.5、存储库模式、Fluent NHibernate、SQL Server 2008

编辑

我在下面的 Porges 答案的帮助下解决了这个问题,所以我接受了它。问题确实来自对 TRelated 的错误使用。这是存储库中的工作方法...

public IQueryable<T> AllWithFetch<T>(IQueryable<T> existing, params Expression<Func<T, Entity>>[] fetchExpressions)
        {
            return fetchExpressions.Aggregate(existing, (current, exp) => current.Fetch(exp));
        }

现在 AllWithFetch 不是 TRelated,我在 Func 中使用两个实体(Case 和 CaseOwner)的超类。

感谢大家的帮助

【问题讨论】:

  • .Case.CaseOwner的返回类型是什么?

标签: c# fluent-nhibernate repository-pattern


【解决方案1】:

问题是你的TRelated,这与params 没有任何关系。

试试这个,例如:

void DoSomething<T,U>(Func<T,U> f, Func<T,U> f2)
{
}

void Main()
{
    DoSomething((int x) => x + 1, (int x) => x + ""); 
}

编译器会推断T 必须是int,但它不能推断出U 的好类型(我不确定确切 细节,但它通常会赢'不要寻找继承链更高的类型)。

要让它工作,你需要指定超类;在这种情况下,object:

void Main()
{
    DoSomething<int,object>((int x) => x + 1, (int x) => x + ""); 
}

因此,您要么需要自己指定一个超类(这里看起来是object),要么就去掉TRelated 参数。

【讨论】:

    【解决方案2】:

    您应该将 TRelated 作为每个函数的返回值。 .Case 和 .CaseOwner 是否具有相同的类型?如果没有,你可以使用

    Func<T, object> 
    

    改为(或任何接口)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多