给定两个具有相同签名的委托(delegate),您可以轻松地从一个转换为另一个。
delegate string d1(string x, params object[] o);
delegate string d2(string x, params object[] o);
var d2instance = new d2(d1instance);
我想转换 Action<d1>进入Action<d2> ,但无法理解如何执行此操作。
class Program
{
private delegate void d1(string x, params object[] o);
private delegate void d2(string x, params object[] o);
private static void DoSomething(string template, params object[] args)
{
Console.WriteLine(String.Format(template, args));
}
private static void Main(string[] args)
{
RunD1(m => m("Foo {0}", 42));
RunD2(m => m("Foo {0}", 42));
}
private static void RunD1(Action<d1> action)
{
action(DoSomething);
}
private static void RunD2(Action<d2> action)
{
// This needs to call RunD1
// RunD1(.....);
}
}
请您参考如下方法:
创建 Action<d2> 的最简单方法来自 Action<d1>通过另一个 lambda 表达式:
Action<d1> original = ...;
Action<d2> converted = x => original(new d1(x));
当然,最好避免完全使用不同的委托(delegate)类型:)
