简体   繁体   中英

Equivalent of typedef in c# for Action<> and/or Func<>

After googling it doesn't look promising, but I'm wondering if there is some way of aliasing or typedef'ing when using Action<T> or Func<in T, out TResult> in C#?

I've already seen Equivalent of typedef in c# , which says that within one compile scope you can use the using construct for some cases, but that doesn't seem to apply to Action 's and Func 's as far as I can tell.

The reason I want to do this is that I want an action to be used as a parameter to several functions, and if I, at some point in time, decide to change the action it's a lot of places to change both as parameter types and as variable types.

?typedef? MyAction  Action<int, int>;

public static SomeFunc(WindowClass window, int number, MyAction callbackAction) {
   ...
   SomeOtherFunc(callbackAction);
   ...
}

// In another file/class/...
private MyAction theCallback;

public static SomeOtherFunc(MyAction callbackAction) {
    theCallback = callbackAction;
}

Are there some construct to use, which can define the MyAction as indicated in the code segment?

After some more searching, it seems as though delegate 's comes to the rescue (see Creating delegates manually vs using Action/Func delegates and A: Custom delegate types vs Func and Action ). Please comment as to why this is not a solution or possible pitfalls.

With delegates I can rewrite the first line the given code example:

public delegate void MyAction(int aNumber, int anotherNumber);
// Keep the rest of the code example

// To call one can still use anonymous actions/func/...
SomeFunc(myWindow, 109, (int a, int b) => Console.Writeline);
using System;

namespace Example
{
    using MyAction = Action<int>;

    internal class Program
    {
    }

   private void DoSomething(MyAction action)
   {
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM