tag*_*s2k 9 c# generics func inline-method
我编写了一个简单的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];
}
Run Code Online (Sandbox Code Playgroud)
现在,我如何实际使用它,将Func <T>作为内联方法参数传递?
Mar*_*ell 16
由于这是一个函数,lambda将是最简单的方法:
Foo foo = GetItem<Foo>("abc", () => new Foo("blah"));
Run Code Online (Sandbox Code Playgroud)
其中[new Foo("blah")]是作为默认调用的func.
您还可以简化为:
return ((T)HttpContext.Current.Session[key]) ?? defaultValue();
Run Code Online (Sandbox Code Playgroud)
哪里?? 是null-coalescing运算符 - 如果第一个arg是非null,则返回它; 否则会评估并返回右手(因此除非该项为null,否则不会调用defaultValue()).
最后,如果您只想使用默认构造函数,那么您可以添加"new()"约束:
public static T GetItem<T>(string key)
where T : new()
{
return ((T)HttpContext.Current.Session[key]) ?? new T();
}
Run Code Online (Sandbox Code Playgroud)
这仍然是懒惰的 - 仅当项目为null时才使用new().
| 归档时间: |
|
| 查看次数: |
22542 次 |
| 最近记录: |