C# - 如何将内联方法 Func<T> 定义为参数?

标签 c# generics func inline-method

我已经编写了一个简单的 SessionItem 管理类来处理所有那些讨厌的 null 检查并在不存在时插入一个默认值。这是我的 GetItem 方法:

public static T GetItem<T>(string key, Func<T> defaultValue)
{
    if (HttpContext.Current.Session[key] == null)
    {
        HttpContext.Current.Session[key] = defaultValue.Invoke();
    }
    return (T)HttpContext.Current.Session[key];
}

现在,我如何实际使用它,将 Func 作为内联方法参数传递?

最佳答案

因为这是一个函数,lambda 将是最简单的方法:

Foo foo = GetItem<Foo>("abc", () => new Foo("blah"));

其中 [new Foo("blah")] 是默认调用的函数。

您还可以简化为:

return ((T)HttpContext.Current.Session[key]) ?? defaultValue();

在哪里??是空合并运算符 - 如果第一个 arg 非空,则返回它;否则评估并返回右手(因此除非项目为空,否则不会调用 defaultValue())。

最后,如果你只想使用默认构造函数,那么你可以添加一个“new()”约束:

public static T GetItem<T>(string key)
    where T : new()
{
    return ((T)HttpContext.Current.Session[key]) ?? new T();
}

这仍然是惰性的 - new() 仅在项目为 null 时才使用。

关于C# - 如何将内联方法 Func<T> 定义为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/156779/

相关文章:

java - Lists.newArrayList 与新的 ArrayList

generics - 创建一个由数字参数化的泛型类型

c# - 如何从函数返回一个 Action ?

oracle - Oracle 中的架构、用户和功能 ID

c# - Trim().Split 在 Contains() 中导致问题

c# - ushort 等价物

c# - 将证书注册到 SSL 端口

c# - 应用程序域和线程

scala - 如何通过scala中的类方法传递类型参数?

c# - 在接口(interface)上使用 Function<>?