【问题标题】:Using new in a Func<T>在 Func<T> 中使用 new
【发布时间】:2009-04-24 18:17:38
【问题描述】:

我想知道,在阅读了this question...之后,他有这个代码:

public static T FindOrCreate<T>(this Table<T> table, Func<T, bool> find) 
    where T : new()
{
    T val = table.FirstOrDefault(find);
    if (val == null)
    {
        val = new T();
        table.InsertOnSubmit(val);
    }
    return val;
}

是否也可以将该新项目作为另一个 Func 发送?我的意思是,当然会。但是,那会已经创建了吗?还是在您实际运行 Func 时首先创建它?假设你有这个:

public static T FindOrCreate<T>(this Table<T> table, Func<T, bool> find, Func<T> replacement) 
    where T : new()
{
    T val = table.FirstOrDefault(find);
    if (val == null)
    {
        val = replacement();
        table.InsertOnSubmit(val);
    }
    return val;
}

然后通过这样做调用它:

var invoiceDb = ctx.Invoices.FindOrCreate(a => a.InvoicerId == InvoicerId
                                            && a.Number == invoiceNumber,
                                          () => new Invoice());
invoiceDb.Number = invoiceNumber;

如果找到该发票,是否会创建新发票?还是该代码在实际调用该函数之前才运行?或者它是如何工作的?

【问题讨论】:

    标签: c# generics function delegates


    【解决方案1】:

    在这种情况下,您将传递一个委托,因此

    () => new Invoice()
    

    直到

    代码才会被调用
    val = replacement();
    

    行

    【讨论】:

      【解决方案2】:

      replacement 中的代码在实际调用该函数之前不会运行,并且发现表中缺少该值。

      顺便说一句,如果您按照说明实现这一点,这是完全合理的——您可能希望从函数中删除“where T : new()”约束,因为它不再需要;你给它所有关于如何构建一个相当明确的信息。

      【讨论】:

      • 这也是真的。我只是从他的答案中复制粘贴了代码,并没有考虑太多:p
      【解决方案3】:

      不,不会创建新发票。 Func 只是一个委托,因此当您创建 lambda: () => new Invoice() 时,它实际上与执行此操作相同:

      public Invoice Create()
      {
         return new Invoice();
      }
      

      并将委托传递给 Create 方法。只有当您真正执行委托(“创建”函数)时,该代码才会真正运行,从而创建发票。

      【讨论】:

        猜你喜欢
        • 2019-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-01
        • 2010-10-22
        相关资源
        最近更新 更多