Martin
Martin

Reputation: 325

Dynamically convert Func to corresponding Action

I'm trying to use the Convert method on functions as well as actions, so I can avoid writing duplicate methods taking in delegates of Func type. Convert method comes from Convert Action<T> to Action<object>

public class Program
{
    static void Main(string[] args)
    {
        var program = new Program();
        var mi = program.GetType().GetMethod("Function", BindingFlags.Instance | BindingFlags.Public);
        // Can be any version of Func
        var funcType = typeof(Func<int, int>);
        // Create action delegate somehow instead
        var del = mi.CreateDelegate(funcType, null);
        // Or dynamically convert the Func to a corresponding Action type (in this case Action<int>)
    }

    // Or find a way to pass it in as a parameter here
    public Action<object> Convert<T>(Action<T> action)
    {
        return o => action((T)o);
    }

    public int Function(int five)
    {
        return five;
    }
}

Upvotes: 2

Views: 5783

Answers (1)

Stuart
Stuart

Reputation: 5506

I think you are looking for something like this:

public static Action<T1> IgnoreResult<T1,T2>(Func<T1,T2> func)
{
    return x => func(x);
}

But for all variants of Func<T1,T2....>

I think this would work:

public static Action<TR> IgnoreResult<TR>(Delegate f)
{
    return x => f.DynamicInvoke(x);
}

With usage:

var action = IgnoreResult<int>(new Func<int,int>(program.Function));
action(5);

You'll not be able to get it to infer the parameters and return type without copy and pasting the first example for all variants of Action<T1...> and Func<T1,T2...>.

Upvotes: 5

Related Questions