Class ExpressionTypeChanger<T>
A class for traversing expressions and changing the type of a parameter from a type to another
This is used by the system for Linq expressions generated against an interface and replacing them to work against the actual class implementation of that interface
Inherited Members
Namespace: LemonEdge.Utils
Assembly: LemonEdge.Utils.dll
Syntax
public class ExpressionTypeChanger<T> : ExpressionVisitor
Type Parameters
Name | Description |
---|---|
T | The type for the original expression |
Remarks
See https://stackoverflow.com/questions/14932779/how-to-change-a-type-in-an-expression-tree for more details
For example:
public interface IMyItem
{
int Value { get; set; }
}
public class MyItem : IMyItem
{
public int Value { get; set; }
public override string ToString() => Value.ToString();
}
public class Example
{
public IEnumerable<MyItem> ChangeType()
{
Expression<Func<IMyItem, bool>> expr = x => x.Value > 10;
var newExpr = ExpressionTypeChanger<IMyItem>.Change<MyItem>(expr);
var items = new List<MyItem>() { new MyItem() { Value = 5 }, new MyItem() { Value = 15 } };
return items.Where(newExpr.Compile());
}
}
Would return: 15
Methods
Change<TT>(Expression<Func<T, bool>>)
Converts an expression from one type to another
Declaration
public static Expression<Func<TT, bool>> Change<TT>(Expression<Func<T, bool>> expr) where TT : T
Parameters
Type | Name | Description |
---|---|---|
Expression<Func<T, bool>> | expr | The original expression to change the type of |
Returns
Type | Description |
---|---|
Expression<Func<TT, bool>> | A new expression with the type replaced |
Type Parameters
Name | Description |
---|---|
TT | The type to convert the original expression into |
Remarks
For example:
public interface IMyItem
{
int Value { get; set; }
}
public class MyItem : IMyItem
{
public int Value { get; set; }
public override string ToString() => Value.ToString();
}
public class Example
{
public IEnumerable<MyItem> ChangeType()
{
Expression<Func<IMyItem, bool>> expr = x => x.Value > 10;
var newExpr = ExpressionTypeChanger<IMyItem>.Change<MyItem>(expr);
var items = new List<MyItem>() { new MyItem() { Value = 5 }, new MyItem() { Value = 15 } };
return items.Where(newExpr.Compile());
}
}
Would return: 15
VisitMember(MemberExpression)
This method is required because PersonData does not implement IPerson and it finds property in PersonData with the same name as the one referenced in expression and declared on IPerson
Declaration
protected override Expression VisitMember(MemberExpression node)
Parameters
Type | Name | Description |
---|---|---|
MemberExpression | node |
Returns
Type | Description |
---|---|
Expression |
Overrides
VisitParameter(ParameterExpression)
This method replaces original parameter with given in constructor
Declaration
protected override Expression VisitParameter(ParameterExpression node)
Parameters
Type | Name | Description |
---|---|---|
ParameterExpression | node |
Returns
Type | Description |
---|---|
Expression |