有投Fun<TEntity, TId>
到Func<TEntity, object>
更快地將Func <T, T2>投射到Func <T, object>?
public static class StaticAccessors<TEntity>
{
public static Func<TEntity, TId> TypedGetPropertyFn<TId>(PropertyInfo pi)
{
var mi = pi.GetGetMethod();
return (Func<TEntity, TId>)Delegate.CreateDelegate(typeof(Func<TEntity, TId>), mi);
}
public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
{
var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedGetPropertyFn");
var genericMi = mi.MakeGenericMethod(pi.PropertyType);
var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
//slow: lambda includes a reflection call
return x => typedGetPropertyFn.Method.Invoke(x, new object[] { }); //can we replace this?
}
}
有沒有辦法來typedGetPropertyFn
到Func<TEntity, object>
轉換,而無需像上面的例子中,返回拉姆達反射代碼更快的方法?
編輯:添加修改的方案
好感謝280Z28領導我失望,我已經包括在下面的最終解決方案的正確道路。我已經爲那些不支持表達式的平臺留下了反射代碼。對於平臺,它顯示26x到27x(13/.5滴答平均值)性能增加得到int
和string
屬性。
public static Func<TEntity, object> ValueUnTypedGetPropertyTypeFn(PropertyInfo pi)
{
var mi = typeof(StaticAccessors<TEntity>).GetMethod("TypedGetPropertyFn");
var genericMi = mi.MakeGenericMethod(pi.PropertyType);
var typedGetPropertyFn = (Delegate)genericMi.Invoke(null, new[] { pi });
#if NO_EXPRESSIONS
return x => typedGetPropertyFn.Method.Invoke(x, new object[] { });
#else
var typedMi = typedGetPropertyFn.Method;
var obj = Expression.Parameter(typeof(object), "oFunc");
var expr = Expression.Lambda<Func<TEntity, object>> (
Expression.Convert(
Expression.Call(
Expression.Convert(obj, typedMi.DeclaringType),
typedMi
),
typeof(object)
),
obj
);
return expr.Compile();
#endif
}
如果我的初始函數返回像Guid這樣的值類型會怎麼樣?然後,在嘗試投射到Func時遇到運行時錯誤。 –
2012-06-15 14:32:47