How to create custom System.Linq.Expression classes in C #?

Can I create custom expression classes? If so, does anyone have any examples? Inheriting from the framework of the Expression abstract class creates a problem in that its constructor accepts the ExpressionType parameter, which is a type of enumeration of the structure - I obviously cannot configure it!

Any ideas?

+4
source share
4 answers

With .net 3.5 you cannot do this because the expression constructor takes on the value of an ExpressionType enumeration, and you cannot add new node types to the enumeration.

You also cannot overload the existing node type, because you cannot inherit any of the "leaf classes" (for example, BinaryExpression), because they are all sealed.

According to the MSDN docs, it looks like you can do this in CLR v4 as long as you override the Reduce method and use the ExpressionType.Extension node type.

+2
source

This is exactly what DLR code should have done on codeplex; in the end, they recreated the entire codebase in another namespace (IIRC) until 4.0 was sent.

This doesn't necessarily go well with the C # compiler; I honestly have not tried.

+1
source

I do not believe that you can extend Expression, but I think you can add some of your extension methods to create expression trees to simplify generation.

For example, maybe you always like to compare 2 rows so that you can add an extension method that returns a tree for comparison. You can also add an expression that calls a function elsewhere in your code so that you can only write expression trees for things that absolutely need to be developed in this way.

0
source

I have not tried this myself either, but I agree with Scott's statement that this should work in version 4.0.

Specifically, the Specpression Tree Spec on CodePlex talks about this NodeType property:

Derived expressions that are not in a common set of nodes in .NET. should return node view Extension

0
source

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


All Articles