I just ran into a problem involving Expressions.
In my class<T> have a field
Dictionary<Expression, ProjectedCollection> mCache;
where both Expression and ProjectedCollection cannot be specified as Expression<T, S> and ProjectedCollection<S> because the S will be different things at runtime:
void AddSomething<S>(Expression<Func<T, S>> projection)
{
if (!mCache.ContainsKey(projection))
{
var runnable = projection.Compile();
var allProjected = from elm in mList
select runnable(elm);
mCache.Add(projection, new ProjectedCollection<S>(allProjected));
}
}
Now at some point where I don’t know S, I want to iterate over everything in my cache and apply the expression to a new thing.
foreach (KeyValuePair<Expression, ProjectedCollection> keyValuePair in mCache)
{
// Want something like
var func = keyValuePair.Key.Compile();
keyValuePair.Value.SignalAdd(func(newThing));
}
But the Compile() method is not available for the un-typed Expression. And casting is also not possible without knowing S.
Does anybody have an idea how to tackle this?
Cast to a
LambdaExpressionand call Compile on it. It will return an untyped delegate. You can…