我尝试在函数和操作上使用 Convert 方法,这样我就可以避免编写接受 Func 类型委托(delegate)的重复方法。转换方法来自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;
}
}
最佳答案
我认为您正在寻找这样的东西:
public static Action<T1> IgnoreResult<T1,T2>(Func<T1,T2> func)
{
return x => func(x);
}
但是对于 Func<T1,T2....>
的所有变体
我认为这会起作用:
public static Action<TR> IgnoreResult<TR>(Delegate f)
{
return x => f.DynamicInvoke(x);
}
使用情况:
var action = IgnoreResult<int>(new Func<int,int>(program.Function));
action(5);
如果不复制并粘贴 Action<T1...>
的所有变体的第一个示例,您将无法让它推断参数和返回类型。和Func<T1,T2...>
.
关于c# - 动态将Func转换为对应的Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41449076/