I want to create a generic to which I can pass a function as a parameter, however this function may include parameters itself so...
int foo = GetCachedValue("LastFoo", methodToGetFoo)
Such that:
protected int methodToGetFoo(DateTime today) { return 2; // example only }
Essentially I want to have a method that will check the cache for a value, otherwise will generate the value based on the passed in method.
Thoughts?
Use a "closure": $(edit_link). click(function(){ return changeViewMode(myvar); }); This creates an anonymous temporary function wrapper that knows about the parameter and passes it to the actual callback implementation.
Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.
Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.
We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.
It sounds like you want a Func<T>
:
T GetCachedValue<T>(string key, Func<T> method) { T value; if(!cache.TryGetValue(key, out value)) { value = method(); cache[key] = value; } return value; }
The caller can then wrap this in many ways; for simple functions:
int i = GetCachedValue("Foo", GetNextValue); ... int GetNextValue() {...}
or where arguments are involved, a closure:
var bar = ... int i = GetCachedValue("Foo", () => GetNextValue(bar));
Use System.Action
and a lambda expression (anonymous method). For example:
public void myMethod(int integer) { // Do something } public void passFunction(System.Action methodWithParameters) { // Invoke methodWithParameters(); } // ... // Pass anonymous method using lambda expression passFunction(() => myMethod(1234));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With