これらの厄介な null チェックをすべて処理し、存在しない場合はデフォルト値を挿入する単純な 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> をインライン メソッド パラメーターとして渡して、これを実際にどのように使用すればよいでしょうか。