我已经编写了一个简单的 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/