mercredi 7 août 2019

Can I convert a sequence of PropertyInfo to an Expression?

I'm writing some validation code that uses reflection to walk an object graph to find types that implement some conventional static methods with a certain attribute.

I end up with the root object, sequence of PropertyInfo to access the class that implements the static method and the MethodInfo for the static method itself.

I want to write a method to invoke the static method, using the root object as a parameter. My current implementation looks something like this.

private static ValidateOptionsResult InvokeValidation<TConfig>(
        TConfig root,
        IImmutableStack<PropertyInfo> path,
        MethodInfo target)
{
    object node = root;
    foreach (var accessorInfo in path)
    {
        node = accessorInfo.GetMethod.Invoke(
                node,
                new object[]
                    {
                    });
    }

    return (ValidateOptionsResult)target.Invoke(
            null,
            new object[]
                {
                    node
                });
}

I haven't tested this yet but I think it explains what I mean.

The question is, is there a better way to do this by building an expression rather than chaining invokes? By better, I mean faster performing when it is actually invoked.





Aucun commentaire:

Enregistrer un commentaire