将 Func 动态转换为对应的 Action

Mar*_*tin 2 c# delegates action func

我正在尝试对函数和动作使用 Convert 方法,因此我可以避免编写接受 Func 类型委托的重复方法。Convert 方法来自Convert Action<T> 到 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Stu*_*art 5

我想你正在寻找这样的东西:

public static Action<T1> IgnoreResult<T1,T2>(Func<T1,T2> func)
{
    return x => func(x);
}
Run Code Online (Sandbox Code Playgroud)

但是对于所有变体 Func<T1,T2....>

我认为这会奏效:

public static Action<TR> IgnoreResult<TR>(Delegate f)
{
    return x => f.DynamicInvoke(x);
}
Run Code Online (Sandbox Code Playgroud)

使用情况:

var action = IgnoreResult<int>(new Func<int,int>(program.Function));
action(5);
Run Code Online (Sandbox Code Playgroud)

你将无法得到它来推断参数和返回值类型没有拷贝和粘贴的第一个例子为所有变体Action<T1...>Func<T1,T2...>