转换Action <delegate> </delegate>

时间:2014-11-28 17:28:16

标签: c# delegates

鉴于两名代表具有相同的签名,您可以轻松地从一个代表转换为另一个代表。

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(.....);
    }
}

1 个答案:

答案 0 :(得分:3)

Action<d2>创建Action<d1>的最简单方法是通过另一个lambda表达式:

Action<d1> original = ...;
Action<d2> converted = x => original(new d1(x));

最好完全避免完全使用不同的委托类型:)

相关问题