Reputation: 136
I would like to store an Expression in class field to be used later.
Here is what i'm trying to do:
public class MyClass
{
private Expression<Func<Type, object>> _expression;
public void SetExpression<T>(Expression<Func<T, object>> expression)
{
_expression = expression;
}
}
Upvotes: 0
Views: 1118
Reputation: 3080
As stated in the comment to the original question by @canton7 you are using <T>
and Type
but they are not the same thing.
A possible solution for this would be this:
public class MyClass<T>
{
private Expression<Func<T, object>> _expression;
public void SetExpression<T>(Expression<Func<T, object>> expression)
{
_expression = expression;
}
}
Using this approach you would need to create the classes using the following
new MyClass<String>();
This would make the _expression
be of type Expression<Func<String, object>>
.
If you can't set T
to a specific type on creation on the object you will need to pass the expression directly into the method you want to use it in, either that or make the type fixed for the stored Expression.
Upvotes: 2
Reputation: 7546
Either create generic class:
public class MyClass<T>
{
private Expression<Func<T, object>> _expression;
public void SetExpression(Expression<Func<T, object>> expression)
{
_expression = expression;
}
}
Or use more "abstract" expression:
public class MyClass
{
private Expression<Func<object, object>> _expression;
public void SetExpression(Expression<Func<object, object>> expression)
{
_expression = expression;
}
}
In both cases if you working with type of input - you can get it by accessing input arguments of expression:
var inputTypesWhichIWantedToBeGeneric = _expression.Parameters.Select(x=> x.Type);
Upvotes: 0
Reputation: 371
Hey is that what you want to achieve ?
public class MyClass<T>
{
private Expression<Func<T, object>> _expression;
public void SetExpression(Expression<Func<T, object>> expression)
{
_expression = expression;
}
}
Upvotes: 0