我编写了一个简单的SessionItem管理类来处理所有这些麻烦的空检查,并在不存在的情况下插入一个默认值.这是我的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>作为内联方法参数?
解决方法
由于这是一个func,lambda将是最简单的方式:
Foo foo = GetItem<Foo>("abc",() => new Foo("blah"));
其中[new Foo(“blah”)]是作为默认值调用的func.
您也可以简化为:
return ((T)HttpContext.Current.Session[key]) ?? defaultValue();
哪里?是null-coalescing运算符 – 如果第一个arg不为null,则返回;否则右侧被评估和返回(所以defaultValue()不被调用,除非该项为空).
最后,如果您只想使用默认构造函数,那么可以添加一个“new()”约束:
public static T GetItem<T>(string key)
where T : new()
{
return ((T)HttpContext.Current.Session[key]) ?? new T();
}
这仍然是懒惰的 – 只有当项目为空时才使用new().