私は謙虚にから、このコードを再目的と私の人生のために覚えていないことができますが、それはかなりいいです。
using System;
using System.Web;
namespace Project.Web.UI.Domain
{
public abstract class SessionBase<T> where T : class, new()
{
private static readonly Object _padlock = new Object();
private static string Key
{
get { return typeof(SessionBase<T>).FullName; }
}
public static T Current
{
get
{
var instance = HttpContext.Current.Session[Key] as T;
lock (SessionBase<T>._padlock)
{
if (instance == null)
{
HttpContext.Current.Session[Key]
= instance
= new T();
}
}
return instance;
}
}
public static void Clear()
{
var instance = HttpContext.Current.Session[Key] as T;
if (instance != null)
{
lock (SessionBase<T>._padlock)
{
HttpContext.Current.Session[Key] = null;
}
}
}
}
}
その背後にある考え方2倍に。作成されるタイプは、必要な唯一のタイプである必要があります。これは基本的には強く型付けされたラッパーです。だから、あなたが情報を拡張しておきたいいくつかのオブジェクトを持っています。そして、道をあなたはMyClass
を拡張
public class MyClass
{
public MyClass()
public string Blah1 { get; set; }
}
、あなたは、AppSettingsまたは中のConst変数に格納し、すべてのキー値を覚えておく必要がしたくありません静的クラス。
そして、あなたのプログラムのどこにでも簡単にクラスを使用できます。それは実際にそれらの厄介なタイプミスのバグを排除するのに役立ちます -
私は維持するためにあなたの必要性をストリングス*あなたは*魔法の完全なプロジェクトを継承することはありません願っ
// Any Asp.Net method (webforms or mvc)
public void SetValueMethod()
{
MyClassSesssion.Current.Blah1 = "asdf";
}
public string GetValueMethod()
{
return MyClassSession.Current.Blah1;
}
1は、これは私が続く傾向にあるパターンです。 –
この文脈では 'const'を使うべきではありません。 'static readonly'はより適切です(そして安全です)。 – EkoostikMartin
それはどのようにあなた自身を繰り返さないという原則を緩和していますか?どこでも同じ1つのライナーを書いていますが、キーのインスタンス文字列ではなく定数変数を使用していますか? – BlackSpy