How can I return from an unprintable expression to a printed one?

I ran into an Expressions problem.

There is a field in my class<T>

 Dictionary<Expression, ProjectedCollection> mCache; 

where both Expression and ProjectedCollection cannot be specified as Expression<T, S> and ProjectedCollection<S> , because S will be different 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 that I do not 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 non-printable Expression . And casting is also impossible without knowing S

Does anyone have any ideas how to handle this?

+4
source share
1 answer

LambdaExpression to LambdaExpression and call compilation. He will return an untyped delegate. You can...

  • ... pass this delegate to one of the Func / Action types
  • ... check its structure with reflection
  • ... use the .DynamicInvoke delegate to call it
+2
source

Source: https://habr.com/ru/post/1414844/


All Articles