我想出了緩存,評論歡迎。
public static ConcurrentDictionary<Tuple<Type, string>,
Func<object, object[], object>> ReflectionCache
{
get
{
if (_ReflectionCache==null) {
_ReflectionCache = new ConcurrentDictionary<Tuple<Type, string>,
Func<object, object[], object>>();
}
return _ReflectionCache;
}
} private static ConcurrentDictionary<Tuple<Type, string>,
Func<object, object[], object>> _ReflectionCache = null;
public static object GetCachedProperty(object obj, string name)
{
Func<object,object[],object> del;
if (!ReflectionCache.TryGetValue(Tuple.Create<Type,string>(obj.GetType(),
name), out del)) {
MemberInfo memberInfo =
(MemberInfo)obj.GetType().GetMember(name).GetValue(0);
PropertyInfo prop = null;
FieldInfo fld = null;
switch(memberInfo.MemberType) {
case MemberTypes.Field:
fld = obj.GetType().GetField(name);
break;
case MemberTypes.Property:
prop = obj.GetType().GetProperty(name);
break;
}
if (prop == null && fld == null)
{
throw new Exception("No property or field named '" + name
+ "' could be found in the context parent.");
}
if (prop!=null) {
prop= obj.GetType().GetProperty(name);
del = prop.GetValue;
} else {
fld = obj.GetType().GetField(name);
del = delegate(object cls,object[] index) {
return fld.GetValue(cls);
};
}
ReflectionCache[Tuple.Create<Type,string>(obj.GetType(),name)]=del;
}
return(del(obj,null));
}
太棒了,就是我在找的東西。這是序列化的Javascript,是的,我已經使用MS。性能在這一點上不是問題,但我正在設計這個功能時考慮可伸縮性。緩存的想法可能適用於此 - 儘管這是針對Web應用程序的。每次加載頁面時都需要訪問屬性。我認爲緩存代理不會跨頁加載,因爲對象不會是同一個實例。任何想法的方式來優化或緩存時,結構將堅持,但不是實例? – 2011-02-25 20:35:14
@jamietre:你可以緩存一個考慮實例的代理(每個類型靜態),即:'Func',然後將實例傳遞給代理以獲得值... –
2011-02-25 20:36:39
@Reed Copsley - 我永遠不會需要多次訪問給定的實例。不過,我需要多次訪問同一個簽名的不同實例。也就是說,一旦我獲得了頁面加載的信息,我就完成了特定的頁面加載。這不會導致不斷增長的緩存,因爲每次「對象」都不一樣嗎?也許我誤解了你。 – 2011-02-25 20:41:42