在执行调用函数之前执行代码 [英] Execute code before the called function is executed
问题描述
我希望能够以某种方式标记功能(也许属性?),这样,当它从任何地方叫,其他的一些代码获取处理参数和返回值,而不是所谓的功能,也可以让功能正常执行。
I would like to be able to mark a function somehow (attributes maybe?) so that when it's called from anywhere, some other code gets to process the parameters and return a value instead of the called function, or can let the function execute normally.
我会用它来轻松缓存。
例如,如果我有一个函数调用ADD10,它是这样的:
For example, if I had a function called Add10 and it would look like this:
int Add10 (int n)
{
return n + 10;
}
如果该函数去使用相同的值反复调用(ADD10(7))它总是会产生相同的结果(17),所以它是没有意义的重新计算每一次。当然,我不会与功能那么简单,因为这做,但我相信你能明白我的意思。
If the function go called repeatedly with the same value (Add10(7)) it would always give the same result (17) so it makes no sense to recalculate every time. Naturally, I wouldn't do it with functions as simple as this but I'm sure you can understand what I mean.
请问C#提供做着什么办法我想?
我需要一种方法来标记为缓存,这样,当有人做ADD10(16)一些代码某处遇到第一个在字典来检查的,我们已经知道16 ADD10价值和回报,如果我们做一个功能,计算,存储,如果我们不回。
Does C# provide any way of doing what I want? I need a way to mark a function as cached so that when someone does Add10(16) some code somewhere is ran first to check in a dictionary is we already know the Add10 value of 16 and return it if we do, calculate, store and return if we don't.
推荐答案
您想memoize的功能。这里有一种方法:
You want to memoize the function. Here's one way:
的 http://blogs.msdn.com/b/wesdyer/archive/2007/01/26/function-memoization.aspx
这篇关于在执行调用函数之前执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!