通用的自定义上下文对象
来源:互联网 发布:金蝶数据库在哪里 编辑:程序博客网 时间:2024/06/05 07:02
/// <summary>
/// 通用的自定义上下文对象
/// </summary>
public class GenericContext
{
/// <summary>
/// 由于内部操作上,所有的容器类型均为 Dictionary<string, object>
/// 所以定义一个固定的类型名称。
/// </summary>
class NameBasedDictionary : Dictionary<string, object> { }
/// <summary>
/// 用于 Windows 应用的线程级上下文成员容器
/// </summary>
[ThreadStatic]
private static NameBasedDictionary threadCache;
/// <summary>
/// 标识当前应用是否为 Web 应用
/// </summary>
private static readonly bool isWeb = CheckWhetherIsWeb();
/// <summary>
/// Web 应用中 Context 保存的键值
/// </summary>
private const string ContextKey = "marvellousWorks.context.web";
/// <summary>
/// 对于 Web 应用,如果HttpContext对应内容元素没有初始化,则放置一个空容器。
/// 对于 Windows 应用,由于 threadCache 为 [ThreadStatic],无需该过程。
/// </summary>
public GenericContext()
{
if (isWeb && (HttpContext.Current.Items[ContextKey] == null))
HttpContext.Current.Items[ContextKey] = new NameBasedDictionary();
}
/// <summary>
/// 根据上下文成员名称,返回对应内容的。
/// <remarks>
/// 由于 threadCache 或 HttpContext 中的缓冲对象都会在构造过程中创建
// 因此,这里没有对 cache == null 的判断。
/// </remarks>
/// </summary>
/// <param name="name">上下文成员键值。</param>
/// <returns>对应内容</returns>
public object this[string name]
{
get
{
if (string.IsNullOrEmpty(name)) return null;
NameBasedDictionary cache = GetCache();
if (cache.Count <= 0) return null;
object result;
if (cache.TryGetValue(name, out result))
return result;
else
return null;
}
set
{
if (string.IsNullOrEmpty(name)) return;
NameBasedDictionary cache = GetCache();
object temp;
if (cache.TryGetValue(name, out temp))
cache[name] = value;
else
cache.Add(name, value);
}
}
/// <summary>
/// 根据应用类型获取相应上下文缓冲对象。
/// </summary>
/// <returns>缓冲对象。</returns>
private static NameBasedDictionary GetCache()
{
NameBasedDictionary cache;
if (isWeb)
cache = (NameBasedDictionary)HttpContext.Current.Items[ContextKey];
else
cache = threadCache;
if (cache == null)
cache = new NameBasedDictionary();
if (isWeb)
HttpContext.Current.Items[ContextKey] = cache;
else
threadCache = cache;
return cache;
}
/// <summary>
/// 判断当前应用是否为 Web 应用的 Helper 方法 (非官方方法)
/// </summary>
/// <returns></returns>
public static bool CheckWhetherIsWeb()
{
bool result = false;
AppDomain domain = AppDomain.CurrentDomain;
try
{
if (domain.ShadowCopyFiles)
result = (HttpContext.Current.GetType() != null);
}
catch (System.Exception){}
return result;
}
}
- 通用的自定义上下文对象
- 更新自定义表时的通用锁对象
- 自定义用户的安全上下文
- 面向对象的 Javascript 上下文
- ContextBoundObject 上下文对象的用法
- 获取 DoradoContext的上下文对象:
- Spring 的上下文Context对象获取
- Android 创建其他应用的上下文对象
- Android上下文对象(Context)的作用
- Android系统的上下文对象Context
- 自定义通用的标题条目
- Android 自定义通用的loadingview
- 自定义对象中文排序,可以指定排序的字段名,较为通用
- Java通用对象池GenericObjectPool<T>原理总结和自定义的Jedis管理池例子
- 打印对象的通用方法
- Android自定义上下文菜单
- 自定义上下文对话框
- contextmenu自定义上下文菜单
- 旅游是一个成长的过程
- RC4加密解密java算法
- svn中文网站
- 通过反射访问属性(Attribute)信息的工具类
- 首次见面
- 通用的自定义上下文对象
- 根据类型名称生成类型实例
- ORACLE ORDER BY用法总结
- C#教学第23讲类的构造2(学习笔记)
- 飞屋环游记
- C# 实现克隆的工具类型
- 机子出错蓝屏,求高手说一下怎么解决!!
- Tourism
- VMWare三种工作模式