I had a part of code that takes in lambda expressions at runtime, which I can then compile and invoke.
Something thing;
Expression<Action<Something>> expression = (c => c.DoWork());
Delegate del = expression.Compile();
del.DynamicInvoke(thing);
In order to save execution time, I stored those compiled delegates in a cache, a Dictionary<String, Delegate>
which the key is the lambda expression string.
cache.Add("(Something)c => c.DoWork()", del);
For exact same calls, it worked fine. However I realized that I could receive equivalent lambdas, such as "d => d.DoWork()", which I should actually use the same delegate for, and I wasn't.
This got me wondering if there was a clean way (read "not using String.Replace", I already did that as a temporary fix) to replace the elements in a lambda expression, like maybe replacing them by arg0
so that both
(c => c.DoWork())
and (d => d.DoWork())
are transformed and compared as (arg0 => arg0.DoWork())
by using something fuctionnally similar to injecting a Expression.Parameter(Type, Name) in a lambda.
Is that possible ? (Answers can include C#4.0)
(f,g) => f.Method(g)
, and I will have the types of f and g. The key is quite mundane actually and isn't set in stone, any suitable way to represent equivalence between 2 lambdas beside((T)arg0,(V)arg1) => arg0.Method(arg1)
could do the trick as the key. – Administrative