(How) is it possible to bind/rebind a method to work with a delegate of a different signature?

前端 未结 2 739
抹茶落季
抹茶落季 2020-12-28 09:58

I\'m a c++ developer having used signals & slots in c++ which to me seems to be analogous to delegates in c#. I\'ve found myself at a loss in searching for the functiona

2条回答
  •  萌比男神i
    2020-12-28 10:13

    Try the following

    class Example {
      static void foo(int i) {
        Console.WriteLine(i);
      }
      public static void Main() {
        Action someCallback = () => foo(5);
        someCallback();
      }
    }
    

    Or for something even closer to the C++ counter part

    class Example {
      static void foo(int i) {
        Console.WriteLine(i);
      }
      static Action bind(Action action, T value) {
        return () => action(value);
      }
      public static void Main() {
        Action someCallback = bind(foo, 5);
        someCallback();
      }
    }
    

    Explanation. What's happening here is that I am creating a new delegate by means of a lambda expression. The lambda is the expression starting with () =>. In this case it creates a delegate accepting no arguments and producing no value. It is compatible with the type Action.

提交回复
热议问题