[Solved] Invoke Delegate With Right Type [closed]


Two options to consider:

  • Use dynamic typing to call a generic method which will return you a Func<object, object> which you can use later by wrapping up an expression-tree-compiled delegate:

    public Func<Object, Object> CreateFunc(object sampleValue)
    {
        dynamic dynamicValue = sampleValue;
        return CreateFuncImpl(dynamicValue); // Dynamic type inference
    }
    
    private Func<Object, Object> CreateFuncImpl<T>(T sampleValue)
    {
        // You could use Delegate.CreateDelegate as another option - 
        // you don't need expression trees here
        var parameter = Expression.Parameter(parameter.GetType(), "x");
        var expression = Expression.Property(arg, "Name");
        var func = Expression.Lambda<Func<T, object>>(expression, parameter)
                             .Compile();
        return (object actualValue) => func((T) actualValue);
    }
    
  • Wrap the property expression in a conversion expression in the expression tree:

    public Func<Object, Object> CreateFunc(object sampleValue)
    {
        var parameter = Expression.Parameter(typeof(object), "x");
        var conversion = Expression.Convert(parameter, sampleValue.GetType());
        var property = Expression.Property(conversion, "Name");
        return Expression.Lambda<Func<object, object>>(property, parameter)
                         .Compile();
    }
    

Both of these assume that you’re doing the creation very rarely and then calling the delegate many times with values of the same type. They may or may not be what you need – it’s hard to tell with weak requirements. They do require that the values you call the function with later are of the right type, of course.

3

solved Invoke Delegate With Right Type [closed]