Let's assume that I have those classes below;
public class FirstClass
{
private SecondClass secondClass;
public SecondClass Second { get => secondClass; private set => secondClass = value; }
}
public class SecondClass
{
private int x;
public int X { get => x; set => x = value; }
}
What I am trying achieve here is creating delegates;
Func<object, object>
: Getter for X in the SecondClass
, but it should work with an object of FirstClass
Action<object, object>
: Setter for X in the SecondClass
, but it should work with an object of FirstClass
With some efforts I was able to create this;
private static Func<object, object> BuildGetter(MethodInfo method)
{
ParameterExpression obj = Expression.Parameter(typeof(object), "obj");
Expression<Func<object, object>> expr =
Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Call(Expression.Convert(obj, method.DeclaringType), method),
typeof(object)),
obj);
return expr.Compile();
}
However this Func<object, object>
only works with an object of SecondClass
while I want to make it work with an object of FirstClass
. So I am far from what I want to achieve here.
The project I am working on is much more complex, but I tried to simplify it. I am trying to get the MethodInfo
for the get property of X
, using reflection starting from the FirstClass
.
So, How can I create getter/setter delegates which will work with the object of the FirstClass
?
Aucun commentaire:
Enregistrer un commentaire