开发者

anonymous delegate hashCode

I thought about creating some cache helper that gets a Func<T> (or some delegate for .Net2.0) calculates its hash code (or any other unique string) and if this has code doesn't exist adds it to the cache开发者_如何学JAVA.

Is that possible at all? Does this approach make sense at all?

How can I tell the difference between:

GetCache(() => string.Format("{0}", 1));

And

GetCache(() => string.Format("{0}", 2))

?


You should not use hash codes to determine uniqueness. That's not what they're there for.

In your example, the two lambda expressions will end up creating separate methods for the delegates... but it's quite possible (not guaranteed) that they'd do this anyway even if the code inside was exactly the same. In other words, I think the whole caching idea is fundamentally not going to work in the way that you're expecting it to.


The problem is that your lambas may include captured variables from outside of their scope so e.g.

String.Format("{0}", i);

will evaluate differently depending on the value of I when it was captured. If it is worth while to do because the delegates that you are invoking are expensive you probably need to build a higher level object that includes your methods and enough metadata to find them back.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜