RaUI/Source/ryControls/Sheng.Winform.Controls/Kernal/FastReflection/FastReflectionPool.cs

96 lines
3.4 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Sheng.Winform.Controls.Kernal
{
/*
* Dictionary<Type, Dictionary<object, TAccessor>>
* type.GetConstructor
* Types数组GetProperty,GetMethod接收的都是一个String
* Types数组Types数组做为缓存的Key
* Eques是不会相同的使
* GetAccessorKeyFunc Type数组做为缓存的构造函数Cache查找缓存中的key
* object的话key时Type数组和object的转换
* FastReflection的目的就是追求高性能
* TKeyType来标识key的类型
*/
/// <summary>
/// 这个缓存是全局的
/// </summary>
/// <typeparam name="TKeyType"></typeparam>
/// <typeparam name="TAccessor"></typeparam>
public abstract class FastReflectionPool<TKeyType, TAccessor> : IFastReflectionPool<TKeyType,TAccessor>
{
private readonly object _mutex = new object();
private readonly Dictionary<Type, Dictionary<TKeyType, TAccessor>> _cache =
new Dictionary<Type, Dictionary<TKeyType, TAccessor>>();
private bool _customCompare = false;
/// <summary>
///
/// </summary>
public bool CustomCompare { get { return _customCompare; } set { _customCompare = value; } }
/// <summary>
///
/// </summary>
/// <param name="key1"></param>
/// <param name="key2"></param>
/// <returns></returns>
protected virtual bool Compare(TKeyType key1, TKeyType key2)
{
return false;
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="key"></param>
/// <returns></returns>
public TAccessor Get(Type type, TKeyType key)
{
TAccessor accessor;
if (this._cache.TryGetValue(type, out Dictionary<TKeyType, TAccessor> accessorCache))
{
TKeyType accessorKey;
if (_customCompare)
{
accessorKey = accessorCache.Keys.Single((k) => { return Compare(k, key); });
}
else
{
accessorKey = key;
}
if (accessorCache.TryGetValue(key, out accessor))
{
return accessor;
}
}
lock (_mutex)
{
if (this._cache.ContainsKey(type) == false)
{
this._cache[type] = new Dictionary<TKeyType, TAccessor>();
}
accessor = Create(type, key);
this._cache[type][key] = accessor;
return accessor;
}
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="key"></param>
/// <returns></returns>
protected abstract TAccessor Create(Type type, TKeyType key);
}
}