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

时间:2020-03-06 14:58:03  来源:igfitidea点击:

我编写了一个简单的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 <T>作为内联方法参数传入?

解决方案

为什么不直接传递默认值?函子有什么用?

顺便说一句,defaultValue.Invoke()非常冗长。也可以只写defaultValue()

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

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

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

我们还可以简化为:

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

在哪里 ??如果第一个arg不为null,则返回null的运算符;如果返回,则返回null。否则,将评估右手并返回右手(因此除非该项为null,否则不会调用defaultValue())。

最后,如果只想使用默认构造函数,则可以添加" new()"约束:

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

仍然很懒,仅当该项为null时才使用new()。

var log = SessionItem.GetItem("logger", () => NullLog.Instance)

注意,通常,我们可以跳过GetItem {T}调用中的{T}规范(如果Func {T}返回相同类型的对象)