I'm trying to determine the equality of two predicates:
public T FirstOrDefault(Func<T, bool> predicate)
{
if (EntityCache.ContainsKey(predicate.GetHashCode()))
return EntityCache[predicate.GetHashCode()];
else
{
var entity = _objectSet.FirstOrDefault<T>(predicate);
EntityCache.Add(predicate.GetHashCode(), entity);
return entity;
}
}
The issue I'm having is the hash code of the predicate开发者_JAVA百科 doesn't account for the values used inside it, and I'm not sure how to go about retrieving them.
If for instance the predicate passed to our method above is: (r => r.Id == id) how would I go about finding the value of 'id' inside my FirstOrDefault method?
You'll need to use Expression's. They contains func's, but they also contain the syntax tree and you can examine their 'source code' at runtime.
If I understand you correctly, you're trying to determine the value of a captured variable inside a delegate. I'm pretty sure there's no easy way to do this... perhaps if you used an expression tree instead of a delegate it would be simpler ?
Another option (probably much simpler) is keeping the values passed to the delegates alongside them in EntityCache
Also note that instead of
if (EntityCache.ContainsKey(predicate.GetHashCode()))
return EntityCache[predicate.GetHashCode()];
It would be better to use TryGetValue
精彩评论