dimanche 5 avril 2020

C# Linq Expression - How to get the instance of an expression

Is there any way to get the used instance from a linq expression as a reference or something else?

At the moment I have the following to declare my expression:

var testClass = new ClassToTest();
otherClass.RunTest(() => testClass.NumberOfCars);

Now I want to get the used instance object from the expression. So that I could later get another property dynamically for example. I know that I can just pass more parameters to the function itself to use them but I wonder if this is also possible by expression.

Update

public class ClassToTest
{
    public int NumberOfCars;
    public int NumberOfChildren;

    public ClassToTest()
    {
        NumberOfCars = 1;
        NumberOfChildren = 2;
    }
}

public class TestingClass<TResult>
{
    public bool RunTest(Expression<Func<TResult>> expression)
    {
        // var numberOfCars = get info with the help of the expression and reflection 
        // var instance = get used instance in expression
        if (instance.NumberOfChildren > 2 && numberOfCars == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

var otherClass = new TestingClass<int>();

It is just a basic example to understand my problem. The example could be better solved to pass both values as a parameter and check them but I wondered if this is possible to archive so.





Aucun commentaire:

Enregistrer un commentaire