Home >Backend Development >C++ >How to Convert a .NET Func to an Expression?
In .NET, a lambda expression can be easily converted into an Expression<> using the Expression class. However, there may be instances where one wishes to convert a Func
Consider the following code:
public void GimmeExpression(Expression<Func<T>> expression) { ((MemberExpression)expression.Body).Member.Name; // "DoStuff" } public void SomewhereElse() { GimmeExpression(() => thing.DoStuff()); }
Here, a lambda expression is passed to the GimmeExpression method, which extracts the name of the method being called (DoStuff).
Now, suppose we want to perform a similar operation but in a restricted context:
public void ContainTheDanger(Func<T> dangerousCall) { try { dangerousCall(); } catch (Exception e) { // This next line does not work... Expression<Func<T>> DangerousExpression = dangerousCall; var nameOfDanger = ((MemberExpression)dangerousCall.Body).Member.Name; throw new DangerContainer( "Danger manifested while " + nameOfDanger, e); } } public void SomewhereElse() { ContainTheDanger(() => thing.CrossTheStreams()); }
In this case, we attempt to convert the dangerousCall Func
Cannot implicitly convert type 'System.Func<T>' to 'System.Linq.Expressions.Expression<System.Func<T>>'. An explicit cast does not resolve the situation.
This is because Func
Disassembling the intermediate language (IL) and inferring the original expression might allow for this conversion if the necessary data has not been optimized away. However, this is a complex and potentially unreliable approach.
The above is the detailed content of How to Convert a .NET Func to an Expression?. For more information, please follow other related articles on the PHP Chinese website!