【问题标题】:Pass function as parameter传递函数作为参数
【发布时间】:2016-10-28 12:06:27
【问题描述】:

我有一个函数:

private static PrivateMessage GetPM()
{
    using (var db = new DBContext())
    {
        var q = CompiledQueries.GetPMByID(db, messageID);
        if (q == null) return null;
        return new PrivateMessage(q);
    }
}

我希望将此函数作为参数传递:

var pm = cacheObj.SetIfNotExists(GetPM);

其中SetIfNotExists定义为:

public T SetIfNotExists<T>(Func<T> getCachableObjectFunction)

我需要修改什么才能将messageID 作为GetPM() 中的参数传递?例如:

private static PrivateMessage GetPM(int messageID)

【问题讨论】:

  • var pm = cacheObj.SetIfNotExists(() => GetPM(1)); ?

标签: c# function generics caching parameters


【解决方案1】:

包装和类型转换您的输出是最简单的方法。

var pm = cacheObj.SetIfNotExists(() => GetPM(1));

并将GetPM 标头更改为:

private static PrivateMessage GetPM(int messageID)

【讨论】:

  • 非常感谢!回答我的下一个问题,即如何为具有不同参数输入的函数执行此操作!只是检查,以这种方式传递它不会调用它吗?
  • 你是对的,它没有,但答案允许你在 GetPM() 方法中传递任意数量的参数。
  • @TomGullen 可能应该只是给出你自己的答案,但现在这是正确的。
猜你喜欢
  • 2013-01-27
  • 2021-04-13
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
相关资源
最近更新 更多